I create several instances of my class in a loop and expect those to be independent. But to my confusion, when I create a new instance with the same name, it keeps properties of the instance created before.
So I have something like:
class myClass(object):
def __init__(self, i1 = None, i2 = 'X', p1 = [], p2 = []):
self.i1, self.i2 = i1,i2
self.property1 = p1
self.property2 = p2
def doStuff(self):
self.property1.append(self.i1)
self.property2.append(self.i2)
print self.property1
print self.property2
class mySubClass(myClass):
def __init__(self, i1 = None, i2 = 'Z'):
myClass.__init__(self, i1, i2)
inputTuples = (('A', 'B'), ('D', 'E'))
for x,y in inputTuples:
o=mySubClass(x)
pprint(vars(o))
o.doStuff()
print(id(o))
{'i1': 'A', 'i2': 'Z', 'property1': [], 'property2': []}
['A']
['Z']
37087832
{'i1': 'D', 'i2': 'Z', 'property1': ['A'], 'property2': ['Z']}
['A', 'D']
['Z', 'Z']
37088392
So for the 1st time it loops, pprint shows o.property1 =[] For the second time, it shows o.property1 is a list of whatever got appended to o in the first run of the loop.
My understanding was that when I call o=myClass(), a new instance of that class would be created and the old one will be deleted (effectively overwrtitten)
Could anyone explain to me how python works here and how I could make it work the way I want?
If I change the class to
class myClass(object):
def __init__(self, i1 = None, i2 = 'X':
self.i1, self.i2 = i1,i2
self.property1 = []
self.property2 = []
it works fine
{'i1': 'A', 'i2': 'Z', 'property1': [], 'property2': []}
['A']
['Z']
37087832
{'i1': 'D', 'i2': 'Z', 'property1': [], 'property2': []}
['D']
['Z']
37088392
I dont understand the fundamental difference here. Also, how can I keep the possibility of having p1 and p2 as input variables and still ahve the desired behaviour?