I made an example python script to show a simplified version of an issue I discovered in my other program. Why is list behaving like a static variable? How can I fix this? Any help would be greatly appreciated. Thanks!
Code:
class MyClass:
id = 0
list = []
def addToList(self,value):
self.list.append(value)
def printClass(self):
print("\nPrinting Class:")
print("id: ", self.id)
print("list: ", self.list)
classes = []
# create 4 classes, each with a list containing 1 string
for i in range(0,4):
myClass = MyClass() # create new EMPTY class
myClass.id = i # assign id to new class
myClass.addToList("hello") # add a string to its list
classes.append(myClass) # save that class in a list
for myClass in classes:
myClass.printClass()
Output:
Printing Class:
id: 0
list: ['hello', 'hello', 'hello', 'hello']
Printing Class:
id: 1
list: ['hello', 'hello', 'hello', 'hello']
Printing Class:
id: 2
list: ['hello', 'hello', 'hello', 'hello']
Printing Class:
id: 3
list: ['hello', 'hello', 'hello', 'hello']