为什么我的列表表现得像一个静态变量?

Why is my list behaving like a static variable?

我制作了一个示例 python 脚本来显示我在其他程序中发现的问题的简化版本。为什么列表表现得像静态变量?我怎样才能解决这个问题?任何帮助将不胜感激。谢谢!

代码:

class MyClass:
    id = 0
    list = []

    def addToList(self,value):
        self.list.append(value)

    def printClass(self):
        print("\nPrinting Class:")
        print("id: ", self.id)
        print("list: ", self.list)


classes = []

# create 4 classes, each with a list containing 1 string
for i in range(0,4):
    myClass = MyClass() # create new EMPTY class
    myClass.id = i # assign id to new class
    myClass.addToList("hello") # add a string to its list
    classes.append(myClass) # save that class in a list

for myClass in classes:
    myClass.printClass()

输出:

Printing Class:
id:  0
list:  ['hello', 'hello', 'hello', 'hello']

Printing Class:
id:  1
list:  ['hello', 'hello', 'hello', 'hello']

Printing Class:
id:  2
list:  ['hello', 'hello', 'hello', 'hello']

Printing Class:
id:  3
list:  ['hello', 'hello', 'hello', 'hello']

__init__ 之外定义的变量由所有实例共享。这就是为什么在列表中添加一个元素会影响此 class.

的所有其他实例的原因

您应该改为在 __init__:

中声明变量
def __init__(self):
    self.id = 0
    self.list = []