“对象没有__dict__,因此您无法将任意属性分配给对象类的实例。”

时间:2017-07-03 07:41:03

标签: python python-3.x

来自https://docs.python.org/3.3/library/functions.html#object

  

object没有__dict__,因此您无法将任意属性分配给object类的实例。

为什么“object没有__dict__”? 它对我有用

>>> object.__dict__
mappingproxy({'__repr__': <slot wrapper '__repr__' of 'object' objects>, '__hash__': <slot wrapper '__hash__' of 'object' objects>, '__subclasshook__': <method '__subclasshook__' of 'object' objects>, '__ne__': <slot wrapper '__ne__' of 'object' objects>, '__format__': <method '__format__' of 'object' objects>, '__new__': <built-in method __new__ of type object at 0xa3dc20>, '__doc__': 'The most base type', '__class__': <attribute '__class__' of 'object' objects>, '__dir__': <method '__dir__' of 'object' objects>, '__delattr__': <slot wrapper '__delattr__' of 'object' objects>, '__getattribute__': <slot wrapper '__getattribute__' of 'object' objects>, '__le__': <slot wrapper '__le__' of 'object' objects>, '__init__': <slot wrapper '__init__' of 'object' objects>, '__gt__': <slot wrapper '__gt__' of 'object' objects>, '__ge__': <slot wrapper '__ge__' of 'object' objects>, '__eq__': <slot wrapper '__eq__' of 'object' objects>, '__reduce__': <method '__reduce__' of 'object' objects>, '__lt__': <slot wrapper '__lt__' of 'object' objects>, '__str__': <slot wrapper '__str__' of 'object' objects>, '__reduce_ex__': <method '__reduce_ex__' of 'object' objects>, '__sizeof__': <method '__sizeof__' of 'object' objects>, '__setattr__': <slot wrapper '__setattr__' of 'object' objects>})

为什么“你不能将任意属性分配给object类的实例”?

1 个答案:

答案 0 :(得分:6)

您将类型上的__dict__与实例上的属性混淆。 object() 实例没有__dict__属性:

 >>> object().__dict__
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'object' object has no attribute '__dict__'

请注意,自定义Python类实例的__dict__属性为descriptor;实例本身没有属性,它是提供它的类(因此返回type(instance).__dict__['__dict__'].__get__(instance))。可能存在object.__dict__,但object.__dict__['__dict__']没有。

object()不支持实例属性,因为它是所有自定义Python类的基础,必须support not having a __dict__ attribute when defining slots instead