为什么从add()方法出来时本地对象没有被破坏

问题描述 投票:0回答:1
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]

python-3.x list object memory-management
1个回答
0
投票
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中的列表有点奇怪。上面的修改使您可以使用新列表


0
投票

这是可变的默认参数陷阱。

def __init__(self,l=[]):

空列表对象是在模块级别创建的,并且对所有Demo实例都是通用的。

请参见"Least Astonishment" and the Mutable Default Argument

© www.soinside.com 2019 - 2024. All rights reserved.