问题描述
我很惊讶地发现子类的类变量无法访问父类的类变量,而无需特别指明父类的类名:
>>>A类(对象):... x = 0...>>>B(A)类:... y = x+1...回溯(最近一次调用最后一次):文件<stdin>",第 1 行,在 <module> 中文件<stdin>",第 2 行,在 B 中NameError: 名称 'x' 未定义>>>B(A)类:... y = A.x + 1...>>>B.x0>>>经过1为什么在定义 B.y 时我必须引用 A.x 而不仅仅是 x?这与我对实例变量的直觉相反,因为我可以在定义 B 后引用 B.x.
在 Python 中,在创建类之前,类的主体在其自己的命名空间中执行(之后,该命名空间的成员成为该命名空间的成员)班级).因此,当解释器到达 y = x+1 时,此时 B 类还不存在,因此没有父类.
有关详细信息,请参阅 http://docs.python.org/reference/compound_stmts.html#class-definitions
I was surprised to to learn that a class variable of a subclass can't access a class variable of the parent without specifically indicating the class name of the parent:
>>> class A(object):
... x = 0
...
>>> class B(A):
... y = x+1
...
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 2, in B
NameError: name 'x' is not defined
>>> class B(A):
... y = A.x + 1
...
>>> B.x
0
>>> B.y
1
Why is it that in defining B.y I have to refer to A.x and not just x? This is counter to my intuition from instance variables, and since I can refer to B.x after B is defined.
In Python, the body of a class is executed in its own namespace before the class is created (after which, the members of that namespace become the members of the class). So when the interpreter reaches y = x+1, class B does not exist yet at that point and, therefore, has no parent.
For more details, see http://docs.python.org/reference/compound_stmts.html#class-definitions
这篇关于python子类访问父类变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!