为什么 `object` class 的实例在 Python 中是不可变的?
Why are instances of the `object` class immutable in Python?
>>> a = object()
>>> a.x = 5
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'object' object has no attribute 'x'
>>> b = lambda:0
>>> b.x = 5
>>> b.x
5
为什么 object
class 的实例没有 __dict__
,导致它表现为语义不可变?选择这种设计的原因是什么?
具体原因:
instances of types defined in C don't have a __dict__ attribute by
default.
如 this question.
中所述
Python 2 is not very helpful in giving an explanation as to why you cannot assign attributes to an object()
, but the documentation for Python 3 provides a bit more information 的文档:
Return a new featureless object. object is a base for all classes. It has the methods that are common to all instances of Python classes. This function does not accept any arguments.
Note: object does not have a __dict__
, so you can’t assign arbitrary attributes to an instance of the object class.
因此,您不能向 object()
添加任意属性的原因似乎是因为 object()
实例没有 __dict__
属性的实现,而不是因为 object()
个实例是不可变的:
>>> hasattr(object(), '__dict__')
False
>>>
另一件有趣的事情,但可能与手头的讨论无关,是虽然对象的 实例 可能没有 __dict__
实现,但 object
class 本身就是:
>>> hasattr(object, '__dict__')
True
至于问题的 为什么 部分,我找不到 object()
没有 __dict__
的确切原因。可能是因为——正如@tdelany 已经在评论中提到的——一个实现细节。如果你真的想要一个明确的答案,你应该 ask Guido himself.
>>> a = object()
>>> a.x = 5
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'object' object has no attribute 'x'
>>> b = lambda:0
>>> b.x = 5
>>> b.x
5
为什么 object
class 的实例没有 __dict__
,导致它表现为语义不可变?选择这种设计的原因是什么?
具体原因:
instances of types defined in C don't have a __dict__ attribute by default.
如 this question.
中所述Python 2 is not very helpful in giving an explanation as to why you cannot assign attributes to an object()
, but the documentation for Python 3 provides a bit more information 的文档:
Return a new featureless object. object is a base for all classes. It has the methods that are common to all instances of Python classes. This function does not accept any arguments.
Note: object does not have a
__dict__
, so you can’t assign arbitrary attributes to an instance of the object class.
因此,您不能向 object()
添加任意属性的原因似乎是因为 object()
实例没有 __dict__
属性的实现,而不是因为 object()
个实例是不可变的:
>>> hasattr(object(), '__dict__')
False
>>>
另一件有趣的事情,但可能与手头的讨论无关,是虽然对象的 实例 可能没有 __dict__
实现,但 object
class 本身就是:
>>> hasattr(object, '__dict__')
True
至于问题的 为什么 部分,我找不到 object()
没有 __dict__
的确切原因。可能是因为——正如@tdelany 已经在评论中提到的——一个实现细节。如果你真的想要一个明确的答案,你应该 ask Guido himself.