파이썬에서 객체에 속성을 추가 할 수없는 이유는 무엇입니까?
이 질문에 이미 답변이 있습니다.
- 객체 클래스 6 답변의 속성을 설정할 수 없습니다.
(Python 쉘로 작성)
>>> o = object()
>>> o.test = 1
Traceback (most recent call last):
File "<pyshell#45>", line 1, in <module>
o.test = 1
AttributeError: 'object' object has no attribute 'test'
>>> class test1:
pass
>>> t = test1()
>>> t.test
Traceback (most recent call last):
File "<pyshell#50>", line 1, in <module>
t.test
AttributeError: test1 instance has no attribute 'test'
>>> t.test = 1
>>> t.test
1
>>> class test2(object):
pass
>>> t = test2()
>>> t.test = 1
>>> t.test
1
>>>
개체가 속성을 추가하는 것을 허용하지 않는 이유는 무엇입니까?
것을 알 수 object
인스턴스는 더없는 __dict__
속성을 :
>>> dir(object())
['__class__', '__delattr__', '__doc__', '__getattribute__', '__hash__', '__init__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__str__']
파생 클래스에서이 동작을 설명하는 예 :
>>> class Foo(object):
... __slots__ = {}
...
>>> f = Foo()
>>> f.bar = 42
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'Foo' object has no attribute 'bar'
에 대한 문서에서 인용 slots
:
[...]
__slots__
선언은 일련의 인스턴스 변수를 취하고 각 인스턴스에 각 변수에 대한 값을 보유하기에 충분한 공간을 예약합니다.__dict__
각 인스턴스에 대해 생성되지 않기 때문에 공간이 절약 됩니다.
편집 : 코멘트에서 ThomasH에 대답하기 위해 OP의 테스트 클래스는 "구식"클래스입니다. 시험:
>>> class test: pass
...
>>> getattr(test(), '__dict__')
{}
>>> getattr(object(), '__dict__')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'object' object has no attribute '__dict__'
and you'll notice there is a __dict__
instance. The object class may not have a __slots__
defined, but the result is the same: lack of a __dict__
, which is what prevents dynamic assignment of an attribute. I've reorganized my answer to make this clearer (move the second paragraph to the top).
Good question, my guess is that it has to do with the fact that object
is a built-in/extension type.
>>> class test(object):
... pass
...
>>> test.test = 1
>>> object.test = 1
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: can't set attributes of built-in/extension type 'object'
IIRC, this has to do with the presence of a __dict__
attribute or, more correctly, setattr()
blowing up when the object doesn't have a __dict__
attribute.
참고URL : https://stackoverflow.com/questions/1285269/why-cant-you-add-attributes-to-object-in-python
'IT Share you' 카테고리의 다른 글
수은을 사용하여 svn : externals를 에뮬레이션 할 수 있습니까? (0) | 2020.11.28 |
---|---|
단일 아포스트로피로 표시된 Rust 유형은 무엇입니까? (0) | 2020.11.28 |
멤버 함수와 함께 std :: bind를 사용하여이 인수에 대해 개체 포인터를 사용합니까? (0) | 2020.11.28 |
C ++ 14에서 쌍 배열의 초기화에 여전히 이중 중괄호가 필요한 이유는 무엇입니까? (0) | 2020.11.28 |
좋은 HAML-> ERB / HTML 변환기가 있습니까? (0) | 2020.11.28 |