Python,作为默认参数的可变对象,有什么解决方法吗?
在上述情况下,是否有任何方法可以在uu init_uu()类a中为可变对象(如列表或类)提供默认参数,但b不受操作a的影响?一种可能性是:Python,作为默认参数的可变对象,有什么解决方法吗?,python,class,object,mutable,Python,Class,Object,Mutable,在上述情况下,是否有任何方法可以在uu init_uu()类a中为可变对象(如列表或类)提供默认参数,但b不受操作a的影响?一种可能性是: 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 一种可能性是: class
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
一种可能性是:
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
你可以试试这个:
class A:
def __init__(self, n=None):
if n is None:
n = [0]
self.data = n
这避免了您在这里面临的最大问题,即,对于“A”类型的每个对象都有相同的列表。您可以尝试以下方法:
class A:
def __init__(self, n=None):
if n is None:
n = [0]
self.data = n
这就避免了您在这里面临的最大问题,即,对于“A”类型的每个对象都有相同的列表。另外:
class A:
def __init__(self, n=None):
if n is None:
n = [0]
self.data = n
原则是它会创建另一个列表。如果一个长列表作为参数传递,内存中将有两个长列表。所以不便之处在于它创建了另一个列表。。。。这就是我删除n的原因
不要认为这样更好,但它可能会让你理解发生了什么
class A:
def __init__(self, n=None):
if n is None:
n = [0]
self.data = n
原则是它会创建另一个列表。如果一个长列表作为参数传递,内存中将有两个长列表。所以不便之处在于它创建了另一个列表。。。。这就是我删除n的原因
不要认为它更好,但它可能会让你理解发生了什么复制所有这些:。可能的复制所有这些:。可能的复制