IT Share you

파이썬에서 객체에 속성을 추가 할 수없는 이유는 무엇입니까?

shareyou 2020. 11. 28. 13:14
반응형

파이썬에서 객체에 속성을 추가 할 수없는 이유는 무엇입니까?


이 질문에 이미 답변이 있습니다.

(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

반응형