class Demo:
def __init__(self,l=[]):
self.l=l
def add(self,x):
t=Demo()
t.l.append(x)
print(t.l)
o1 = Demo()o2 = Demo()o1.add(1)o2.add(2)
输出:[1][1,2]
class Demo:
def __init__(self, l=[]):
self.l = l[:]
def add(self, x):
t = Demo()
t.l.append(x)
print(t.l)
o1 = Demo()
o2 = Demo()
o1.add(1)
o2.add(2)
Python中的列表有点奇怪。上面的修改使您可以使用新列表
这是可变的默认参数陷阱。
def __init__(self,l=[]):
空列表对象是在模块级别创建的,并且对所有Demo
实例都是通用的。