ViFI ViFI - 1 month ago 4x
Python Question

Python class shared variables gives unexpected output

Based on the explanation on Shared Variables in Python Class here , I expected the following code to give output as :

123 123
200 200
300 300

But it is

123 123
200 123
200 300


class A:
abc = 123
def __init__(self, a,b,c):
self._a = a
self._b = b
self._c = c

if __name__ == '__main__':
a = A(2, 4, 6)
b = A(3, 9, 27)

print , = 200
print , = 300
print ,

Can somebody please help understand this ? My impression is that shared variables are same as static variables in C++ classes. Any insights to bust that myth, if it is so, would be helpful too.


Initially, the class A has an abc defined to be 123, which each of a and b use since neither has an abc of their own.

Then you execute = 200, which creates an abc for a; b still uses the one from A.

Then you execute = 300, which updates the abc for A, which b still looks to, so it see the new value. But a has its own abc, and so doesn't care.