【问题标题】:Why custom types accept ad-hoc attributes in Python (and built-ins don't)?为什么自定义类型接受 Python 中的临时属性(而内置不接受)?
【发布时间】:2011-03-23 09:59:28
【问题描述】:

我想知道为什么可以为自定义类型的实例创建一个新属性(“new”表示“以前未在类主体中定义”),但不能为一个内置类型,例如 object 本身。

代码示例:

>>> class SomeClass(object):
...     pass
... 
>>> sc = SomeClass()
>>> sc.name = "AAA"
>>> sc.name
'AAA'
>>> obj = object()
>>> obj.name = "BBB"
Traceback (most recent call last):
  File "<console>", line 1, in <module>
AttributeError: 'object' object has no attribute 'name'

【问题讨论】:

    标签: python attributes datamodel custom-type


    【解决方案1】:

    某些对象没有 __dict__ 属性(这是一个存储所有自定义“新定义”属性的字典)。您可以使用 __slots__ 变量模拟相同的行为(请参阅python reference)。当您使用 __dict__ 子类化一个类时,__slots__ 变量不起作用。由于您总是将 object 子类化为新样式类,因此 object 不能有 __dict__,因为这会导致无法使用 __slots__。没有 __slots__ 的类占用更少的内存并且可能会稍微快一些。

    【讨论】:

      猜你喜欢
      • 2017-10-14
      • 1970-01-01
      • 1970-01-01
      • 2020-04-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-07-21
      相关资源
      最近更新 更多