Sheldon Rong Sheldon Rong - 3 months ago 18
Python Question

Python class member inheritance

Can someone provides a detail explanation why this is happening? How does Python compiler create class variables in this case?

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?

Answer

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 B.y, and since there is no y entry in B, it checks its parent class. It does find a y entry in A, with a value of 2. y is defined only once.

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