为什么我的列表表现得像静态变量?
我制作了一个示例 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在
__init__
外部定义的变量由所有实例共享。这就是为什么在列表中添加元素会影响此类的所有其他实例。您应该在 __init__ 中声明变量:
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__
: