[英]Inheritance of class attributes?
Can someone provides a detail explanation why this is happening? 有人可以提供详细解释为什么会发生这种情况吗? How does Python compiler create class variables in this case?
在这种情况下,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?
Because class variables are evaluated at the same time the class itself is evaluated. 因为类变量是同时评估的,所以类本身也是评估的。 Here the sequence of events is:
A
is defined and the values in it are set, so x
is 1 and y
is 2. Then B
is defined, and the x
entry in B
is set to 10. Then you access By
, and since there is no y
entry in B
, it checks its parent class. 这里的事件的序列是:
A
定义并在它的值被设定,因此x
是1和y
是2。然后B
定义,且x
在条目B
设置为10。然后访问By
,并且由于B
没有y
条目,它检查其父类。 It does find a y
entry in A
, with a value of 2
. 它的确在
A
中找到y
条目,其值为2
。 y
is defined only once. y
仅定义一次。
If you really want such a variable, you may want to define a class method. 如果确实需要这样的变量,则可能需要定义一个类方法。
class A:
x = 1
@classmethod
def y(cls):
return cls.x + 1
class B(A):
x = 10
>>> B.y()
11
This is because y
is a class attribute that belongs to A, so changing the value of x in a class instance of B
does not change the value of y
. 这是因为
y
是属于A的类属性,因此在B
的类实例中更改x的值不会更改y
的值。 You can read more about that in the documentation: https://docs.python.org/2/tutorial/classes.html#class-objects 您可以在文档中阅读有关此内容的更多信息: https : //docs.python.org/2/tutorial/classes.html#class-objects
It does not do that. 它不会那样做。
>>> class A(object):
... x = 1
... y = x + 1
...
>>> class B(object):
... x = 10
...
>>> B.x
10
>>> B.y
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: type object 'B' has no attribute 'y'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.