简体   繁体   English

类属性的继承?

[英]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.

相关问题 继承类属性(python) - inheritance on class attributes (python) 外部 class 属性未传递给内部 class python 的属性 inheritance - Outer class attributes not passing to inner class Attributes for python inheritance 自动继承所有基类属性 - Automatic inheritance of all base class attributes 继承而不继承,是否存在创建指向其他类变量的动力学属性? - Inheritance without inheriting, is there create dinamically attributes that point to other class variables? 在Django多表继承中访问子模型类属性 - Access child model class attributes in multi table inheritance in Django 在对象之间链接公共类属性的方法? (不是继承) - Methods to link common class attributes between objects? (not inheritance) Python:确保 class 属性不在常见 inheritance 树之间共享 - Python: ensure class attributes are not shared between common inheritance trees 如何返回 inheritance 链中所有 class 的属性? - How can I return the attributes for all class in the inheritance chain? Python Meta类和继承-无法识别的属性(django-tables2) - Python Meta class and inheritance — attributes not recognized (django-tables2) 带有继承的pytest参数化夹具-子类没有属性 - pytest parametrized fixture with inheritance - child class has no attributes
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM