我无法理解对象实例和对象继承实例之间的区别:
1.__dict__
、__module__
、__weakref__
- 这个属性来自哪里?
>>> dir(object)
['__class__', '__delattr__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__']
>>> dir(type('tt',(object,),{}))
['__class__', '__delattr__', '__dict__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__']
2.我无法为对象实例设置属性。
>>> b= object()
>>> b.f = 3
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'object' object has no attribute 'f'
>>> b = type('tt',(object,),{})()
>>> b.f = 4
这种差异是否来自内置类型生成器?为什么?
最佳答案
1.
__dict__
是每个 python 对象存储其变量的字典,例如。 foo.x
将查找 foo.__dict__['x']
(某些类使用 __slots__
来代替以节省空间)
__module__
指的是该类的模块。
>>> object.__module__
'__builtin__' # object is part of the builtin module
__weakref__
是对象的引用,weakref
模块使用它来保留对对象的引用,而不影响引用计数垃圾收集系统。请参阅here因为它的用途。
2.
您无法在 object()
实例上设置属性,因为它没有 __dict__
,
>>> dir(object)
['__class__', '__delattr__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__']
它仅用作所有其他类的基类,并且不需要一个基类。
像您一样使用 type
实际上创建了 object
的子类,并且您还为其属性赋予了 {}
,所以当然b.f = 4
可以工作。
关于python - 对象及其继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15567571/