1

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?
martineau
124k29 gold badges181 silver badges319 bronze badges
asked Aug 25, 2016 at 0:15
0

3 Answers 3

5

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
answered Aug 25, 2016 at 0:21
Sign up to request clarification or add additional context in comments.

3 Comments

That was clearly what was meant though, it was tagged inheritance.
Both A and B inherit from object.
The OP's code has now been edited. I noticed that B did not inherit from A, but based on the context of the question it was clearly meant to.
1

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. You can read more about that in the documentation: https://docs.python.org/2/tutorial/classes.html#class-objects

answered Aug 25, 2016 at 0:22

1 Comment

Specifically, the value of y is fixed using the value of x at the time it is defined.
-1

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'
answered Aug 25, 2016 at 0:21

2 Comments

I suspect that OP meant to write class B(A).
Why the downvote? This demonstrates that A and B do not share variables even though they both inherit from the same parent class.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.