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

发布于 2025-01-10 06:31:00 字数 1050 浏览 0 评论 0原文

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

代码:

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']

I made an example python script to show a simplified version of an issue I discovered in my other program. Why is list behaving like a static variable? How can I fix this? Any help would be greatly appreciated. Thanks!

Code:

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()

Output:

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']

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

太阳哥哥 2025-01-17 06:31:00

__init__ 外部定义的变量由所有实例共享。这就是为什么在列表中添加元素会影响此类的所有其他实例。

您应该在 __init__ 中声明变量:

def __init__(self):
    self.id = 0
    self.list = []

Variables defined outside of __init__ are shared by all instances. That's why adding an element in the list impacts all other instances of this class.

You should instead declare the variable in __init__:

def __init__(self):
    self.id = 0
    self.list = []
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文