1

I have the following Python class

class MyClass:
    def __init__(self, my_list = []):
        self.my_list = my_list
    
    def addItem(self, item):
        self.my_list.append(item)

And I'm trying to create several objects from that class. However, my_list continues to be shared between the different instances.

For example, with the following two initializations

first_instance = MyClass()
first_instance.addItem("One")
first_instance.addItem("Two")

print(first_instance.my_list)

second_instance = MyClass()
print(second_instance.my_list)

I get the following output

['One', 'Two']
['One', 'Two']

I would have expected the second_instance.my_list to produce an empty list.

What am I missing?

Tarek Oraby
  • 1,199
  • 6
  • 11

1 Answers1

4

Change to

class MyClass:
    def __init__(self, my_list = None):
        self.my_list = my_list if my_list is not None else []
md2perpe
  • 3,372
  • 2
  • 18
  • 22