继承类属性?

She*_*ong 1 python inheritance

有人可以提供详细解释为什么会这样吗?在这种情况下,Python编译器如何创建类变量?

class A(object):
    x = 1
    y = x + 1

class B(A):
    x = 10

>>> B.x
10
>>> B.y
2  # ---> I was expecting 11 here, why does this y still uses the A's value?
Run Code Online (Sandbox Code Playgroud)

spr*_*ceb 5

因为类变量是在评估类本身的同时计算的.这里的事件序列是:A定义并且其中的值被设置,因此x是1并且y是2.然后B定义,并且x条目B设置为10.然后您访问B.y,并且因为没有y条目B,所以检查其父类.它确实找到了一个y条目A,其值为2.y只定义一次.

如果你真的想要这样一个变量,你可能想要定义一个类方法.

class A:
    x = 1

    @classmethod
    def y(cls):
        return cls.x + 1

class B(A):
    x = 10

>>> B.y()
11
Run Code Online (Sandbox Code Playgroud)