python - 对象及其继承

标签 python python-2.7

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

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/

相关文章:

python - 在 neo4j 算法查询中提交参数

python - 如何使用共享库组织和部署云函数项目?

python - 排序算法效率对比

python - Pandas 数据透视表中的小计

Python 2.7 super 方法看不到子类名称

python - 如何在 Python 上使用 PMML 文件和 Augustus 对线性模型进行评分

当最终类没有 __init__ 时不调用 Python mixin 构造函数

python - 如何在 Tkinter 文本框上设置对齐方式

python - 检查 type() 并更改 str() 或 int()

python-2.7 - 当要拟合的参数之一是幂时,SciPy curve_fit 不起作用