0

I want to change the attribute of the instance of T, but when I call update_command_list function of t1, all the attributes of the instances of this class are changed.

If I want to only change the attribute of the instance, how should I change my code?

class T():
    def __init__(self, command_list=['a', 'b', 'c']):
        self.command_list = command_list

    def update_command_list(self):
        self.command_list.append('d')

L = []
t1 = T()
t2 = T()
L.append(t1)
L.append(t2)
L[0].update_command_list()
print(L[0].command_list)
print(L[1].command_list)

The output is ['a', 'b', 'c', 'd'] ['a', 'b', 'c', 'd']

What I want is ['a', 'b', 'c', 'd'] ['a', 'b', 'c']

Elegant Lin
  • 25
  • 2
  • 10

1 Answers1

1

You need to change your __init__() to remove the default argument. Something like:

def __init__(self):
    self.command_list = ['a', 'b', 'c']

Then read the following SO question to understand how default arguments work in python: "Least Astonishment" and the Mutable Default Argument

benvc
  • 14,448
  • 4
  • 33
  • 54