为什么自定义类型接受 Python 中的临时属性(而内置类型不接受)?
我想知道为什么人们能够为自定义类型的实例创建一个新属性(“新”意味着“先前未在类主体中定义”),但无法为内置类型执行相同的操作在类型上,就像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'
I'd like to know why one is able to create a new attribute ("new" means "not previously defined in the class body") for an instance of a custom type, but is not able to do the same for a built-in type, like object
itself.
A code example:
>>> 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'
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
有些对象没有 __dict__ 属性(这是存储所有自定义“新定义”属性的字典)。您可以使用 __slots__ 变量模拟相同的行为(请参阅 Python 参考)。当您使用 __dict__ 子类化类时,__slots__ 变量不起作用。由于您始终为新样式类创建 object 子类,因此 object 不得具有 __dict__,因为这将导致无法使用 __slots__。没有 __slots__ 的类占用更少的内存,并且速度可能稍快一些。
Some objects don't have the __dict__ attribute (which is a dictionary that stores all the custom 'newly defined' attributes). You can emulate the same behaviour using the __slots__ variable (see python reference). When you are subclassing a class with __dict__, the __slots__ variable has no effect. And as you are always subclassing object for new style classes, the object mustn't have __dict__, as that would make it impossible to use __slots__. The classes without __slots__ take less memory and are probably slightly faster.