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']

1
  • change self.command_list = command_list to self.command_list = command_list[:] Commented Dec 20, 2018 at 4:34

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.