How to re-initialize a class object in Python?

Viewed 50

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?

1 Answers

Change to

class MyClass:
    def __init__(self, my_list = None):
        self.my_list = my_list if my_list is not None else []
Related