1

我无法理解对象实例和对象继承实例之间的区别:

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

这种差异是否来自内置类型构建器?为什么?

4

2 回答 2

1

首先,有些类型是不可变的。int并且tuple是不可变的,例如,一个普通的object实例也是如此。同样的限制不适用于子类;您可以子类int化并赋予它可变属性,这同样适用于object.

__dict__属性由类构建器 ( type()) 添加到自定义类;它是类的命名空间映射;类上的属性查找被转换为该结构中的键查找。object另一方面是 Python C 类型,C 中的属性和方法的处理方式不同。Python C 类型应该实现C Type 接口。对于某些类型.__dict__可以取消引用,但您会发现它是一个只读代理对象,因为 C 类型不能像自定义类型那样动态更改。

__module__属性在和上可用objectint

>>> object.__module__
'builtins'
>>> int.__module__
'builtins'

但是因为这些是内置类型,所以该属性实际上没有什么意义,并且没有在dir().

__weakref__属性是weakref模块的实现细节。如果没有在类上设置属性,则构造函数与__dict__属性一起在自定义类上设置此属性。就像属性一样,您发现自定义类和 C 类型对象之间的另一个区别。对于 Python C 类型,C 类型对象结构中的不同条目具有相同的作用。type()__slots____dict__

于 2013-03-22T11:16:19.700 回答
1

1.

__dict__是每个 python 对象具有的存储它的变量的字典,例如。foo.x将查找foo.__dict__['x'](某些类__slots__改为使用以节省空间)

__module__指类的模块。

>>> object.__module__
'__builtin__' # object is part of the builtin module

__weakref__是对对象的引用,weakref模块使用它来保持对对象的引用,而不影响引用计数垃圾收集系统。有关它的用途,请参见此处

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会起作用。

于 2013-03-22T10:22:59.657 回答