我很惊讶地发现子类的类变量无法访问父类的类变量而没有明确指出父类的类名:
>>> 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
Run Code Online (Sandbox Code Playgroud)
为什么在定义中我必须引用Ax而不仅仅是x?这与我对实例变量的直觉相反,因为我可以在定义B之后引用Bx.