Python中的以下代码有什么问题?

时间:2018-04-04 12:05:37

标签: python class static

下面是在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:我已经在下面了解过。

Static class variables in Python -- Lists & Objects

How to avoid having class data shared among instances?

0 个答案:

没有答案