Python类继承和__dict__查找 [英] Python class inheritance and __dict__ lookup

查看:194
本文介绍了Python类继承和__dict__查找的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我定义了A类:

>>> class A:
...     a = 1
...     class SubA:
...         sub_a = { 'a': 1, 'b': 1}

然后我定义从A继承的类B:

Then I define class B that inherits from A:

>>> class B(A):
...     pass

现在,检查A的 __ dict __ 和B的 __ dict __ :

Now, check __dict__ of A and __dict__ of B:

>>> A.__dict__
{'a': 1, '__module__': '__builtin__', '__doc__': None, 'SubA': <class __builtin_ _.SubA at 0x02CAA3E8>}
>>> B.__dict__
{'__module__': '__builtin__', '__doc__': None}

以某种方式, B .__ dict __ 不包含'a''SubA'. 现在,如果这样做:

Somehow, B.__dict__ contains neither 'a' nor 'SubA'. Now if we do:

>>> A.a
1
>>> B.a
1

>>> A.SubA
<class __builtin__.SubA at 0x02CAA3E8>
>>> B.SubA
<class __builtin__.SubA at 0x02CAA3E8>

第一个问题:为什么 B .__ dict __ 不包含'a''SubA'? 第二个问题:为什么'a''SubA'都不在 B 的<强> __ dict __ ?

First question: why B.__dict__ does not contain 'a' and 'SubA'? Second question: Why B.a and B.SubA give the expected results, although neither 'a' nor 'SubA' is in B's __dict__?

谢谢!

推荐答案

@bgporter为行为提供了很好的解释,我只介绍一下为什么:

@bgporter has given a good explanation of the behaviour, I'll just go into why a little:

如果您的类变量在B.__dict__中,它将如何运行?每个子类都有自己的a值,与A.a的值无关-这不是您所期望的.一个类变量应该只存在一次-在该类中.

If your class variable was in B.__dict__, how would it function? Each subclass would have it's own value for a, independent of the value for A.a - this is not what you would expect. A class variable should exist once - in that class.

相反,Python对类进行查找,如果不存在,则查找其基类-请注意,这意味着可以在子类中隐藏类变量.

Instead, Python does a lookup on the class and if it doesn't exist, then looks up to it's base classes - note that means it is possible to shadow a class variable in a subclass.

这篇关于Python类继承和__dict__查找的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆