如何修改实例属性而不是 Python 中的 class 属性

How to modify the instance attribute rather than the class attribute in Python

我想改变T实例的属性,但是当我调用t1的update_command_list函数时,这个class实例的所有属性都被改变了。

如果我只想更改实例的属性,应该如何更改我的代码?

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)

输出是 ['a'、'b'、'c'、'd'] ['a', 'b', 'c', 'd']

我想要的是 ['a'、'b'、'c'、'd'] ['a', 'b', 'c']

您需要更改 __init__() 以删除默认参数。类似于:

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

然后阅读以下 SO 问题以了解默认参数在 python 中的工作原理:"Least Astonishment" and the Mutable Default Argument