0

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']
martineau
  • 119,623
  • 25
  • 170
  • 301
dobs
  • 13
  • 1
  • Also [How to avoid having class data shared among instances?](https://stackoverflow.com/q/1680528/4046632) – buran Feb 26 '22 at 20:59

1 Answers1

2

Variables defined outside of __init__ are shared by all instances. That's why adding an element in the list impacts all other instances of this class.

You should instead declare the variable in __init__:

def __init__(self):
    self.id = 0
    self.list = []
Cubix48
  • 2,607
  • 2
  • 5
  • 17