我很惊讶地发现子类的类变量不能访问父类的类变量,除非明确指定父类的类名:
>>> 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
为什么在定义B.y时我必须引用A.x而不是只引用x?这与实例变量的直觉相反,因为在定义B之后,我可以引用B.x。
class B(super=A): y = super.x + 1
。(我知道super
函数的神奇力量,但我感到害怕。) - Alexey