对象及其继承
我无法理解的对象实例和对象继承实例之间的区别:对象及其继承
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.我不能将propetry设置为对象实例。
>>> 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
会工作。
首先,一些类型是不可变的。例如,int
和tuple
是不可变的,因此是普通的object
实例。同样的限制不适用于子类;你可以继承int
并赋予它可变属性,这同样适用于object
。
__dict__
属性由类构建器(type()
)添加到自定义类中;它是该类的名称空间映射;在类中的属性查找被转换为该结构中的键查找。另一方面,object
是Python C类型,C中的属性和方法处理方式不同。预计Python C类型将实现C Type interface。对于某些类型,可以取消引用.__dict__
,但是您会发现它是只读代理对象,因为C类型不能像自定义类型那样动态更改。
的__module__
属性提供上object
和int
:
>>> object.__module__
'builtins'
>>> int.__module__
'builtins'
但由于这些内置类型的属性是没有意义真的,而不是在dir()
上市。
__weakref__
属性是weakref
module的实施细节。如果没有在该类上设置__slots__
attribute,则与__dict__
属性一起,type()
构造函数在自定义类上设置此属性。像__dict__
属性一样,您发现自定义类和C类对象之间存在另一个区别。对于Python C类型,C type object structure中的不同条目填充相同的角色。