Reputation: 1049
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
Code:
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 a.abc , b.abc
a.abc = 200
print a.abc , b.abc
A.abc = 300
print a.abc , b.abc
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.
Upvotes: 1
Views: 105
Reputation: 1049
@Scott Hunter's answer explains the behavior of code in question best but I would like to add C++ perspective to it here. Unfortunately it couldn't be added as comment in that answer as it is too long.
As in C++, to access static members name needs to be qualified by class name (e.g. A::abc
or A::func_static()
) , in Python also you have to access the shared variable outside the class using Class name as qualifier.
Within the class, C++ allows to use the static variable name as like other member variables (i.e. without any qualifier) and same is true with Python as well, as shared variables can be accessed using self such as self.abc
here.
Only thing which is different here is Python allows you to create an instance variable with the same name as shared variable for that instance only.
Upvotes: 0
Reputation: 3525
You are creating a new instance variable -> a.abc
and setting it to 200
. Access the shared static variable instead.
a = A(2, 4, 6)
b = A(3, 9, 27)
print a.abc , b.abc
A.abc = 200 # Set static class variable, instead of creating new instance member
print a.abc , b.abc
A.abc = 300
print a.abc , b.abc
I recommend reading the very informative Python official docs on [9] Classes.
Upvotes: 4
Reputation: 1841
Your expected output would mean that you can't change the attribute of an object without changing the attribute of every instance of the objects class. That would obviously break the core of the object orientation idea. I think you can overwrite "shared" variables because this gives just more possibilities.
Upvotes: -1
Reputation: 49813
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 a.abc = 200
, which creates an abc
for a
; b
still uses the one from A
.
Then you execute A.abc = 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.
Upvotes: 4