下面是在python中创建可变非静态类变量的文档化方法。
1
它有效(样本输出......)
class Cla:
def __init__(self):
self.arr = []
def showIds(self):
print(str(id(self.arr)))
def show(self):
print(self.arr)
a = Cla()
b = Cla()
a.showIds()
b.showIds()
a.arr.append(10)
b.arr.append(20)
a.show()
b.show()
但是,要在创建时接受一些参数,我将140174126200712
140174126185032
[10]
[20]
修改为以下。 (仅在__init__
函数中进行更改。
__init__
突然间,这份名单就变成了共享。
class Cla:
def __init__(self, arr=[]):
self.arr = arr
def showIds(self):
print(str(id(self.arr)))
def show(self):
print(self.arr)
a = Cla()
b = Cla()
a.showIds()
b.showIds()
a.arr.append(10)
b.arr.append(20)
a.show()
b.show()
我的问题是为什么?上述方法有什么问题。
PS:我已经在下面了解过。