I define a class, and a function which creates an instance of that class. I thought this function should create a new instance every time. However, it looks like it "inherits" its content from last call. Anyone can explain this? Thanks!
class test:
a = []
def b(self,x):
self.a.append(x)
def add():
t = test()
t.b(2)
return t
if __name__ == '__main__':
print add().a
print add().a
print add().a
Output:
[2]
[2, 2]
[2, 2, 2]
Here's how the definition of the a instance variable should look:
class test(object):
def __init__(self):
self.a = []
The way it was before a was not declared as an instance variable, but a class variable that was being shared across all instances of the class.
You defined a as a class variable. It's not bound to an instance of your class, but to the class itself, so there's only one list that's "shared" across the instances of the class.
You need to make it an instance variable:
class test:
def b(self, x):
self.a = []
self.a.append(x)
Also, you should inherit from object in order to utilize new-style classes:
class test(object):
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With