All*_*len 1 python class object mutable
class A:
def __init__(self, n=[0]):
self.data = n
a = A()
print a.data[0] #print 0
a.data[0] +=1
b = A()
print a.data[0] #print 1, desired output is 0
Run Code Online (Sandbox Code Playgroud)
在上面的例子中,有没有办法在__init __()类A中提供带有可变对象(如列表或类)的默认参数,但是b不受操作a的影响?
你可以试试这个:
class A:
def __init__(self, n=None):
if n is None:
n = [0]
self.data = n
Run Code Online (Sandbox Code Playgroud)
这避免了您在这里面临的最大问题,也就是说,对于您的类型"A"的每个单个对象,它都是相同的列表.