Reputation: 23
I need explanation about code below
class Test():
a_variable = []
def add(self, value):
self.a_variable.append(value)
def print(self):
print(self.a_variable)
a = Test()
b = Test()
a.add(1)
b.print()
Output
[1]
Questions:
a_variable
shared to other instance?Note: I'm using python 3.7.4 in my environment and running on Windows 10
Upvotes: 2
Views: 63
Reputation: 59164
Normally when you try to set a class attribute using an instance, you create an object attribute that shadows the class attribute. For example, if you do the following:
def add(self, value):
self.a_variable = value
You will end up with:
a.print()
will print 1
b.print()
will print []
By using .append()
, you fetch a reference to the class attribute (i.e. Test.a_variable
) and mutate it. That's why it is reflected to all instances of the class.
Upvotes: 4