班级中的怪异名单行为 [英] Weird list behavior in class
问题描述
我写了一个具有列表作为变量的类.我有一个添加到该列表的函数和一个输出该列表的函数.
I've written a class that has a list as a variable. I have a function that adds to that list and a function that outputs that list.
class MyClass:
myList = []
def addToList(self, myNumber):
self.myList.append(myNumber)
def outputList(self):
for someNumber in self.myList:
print someNumber
现在出于某些奇怪的原因,如果我声明了该类的两个单独的对象,则:
Now for some weird reason, if I declare two separate objects of the class:
ver1 = MyClass()
ver2 = MyClass()
,然后在ver1上调用addToList:
and then call addToList on ver1:
ver1.addToList(3)
,然后输出ver2的列表:
and then output ver2's list:
ver2.outputList()
我得到3作为版本2列表的输出!发生什么事了?
I get 3 as output for version 2's list! What is happening?
推荐答案
您的语法错误.您正在使用类静态变量.考虑一下:
Your syntax is wrong. You are using a class-static variable. Consider this:
class MyClass:
myList = [] # Static variable
def __init__(self):
self.myRealList = [] # Member variable
myList实际上是MyClass定义的一部分,因此不仅可见于类名,而且可见于该类的所有实例:
myList is actually a part of the MyClass definition, and thus is visible not only by the class name, but all instances of that class as well:
c = MyClass()
c.myList = [1]
print MyClass.myList # will print [1]
您需要在__init__
构造函数中声明常规的成员变量".
You need to declare regular "member variables" in the __init__
constructor.
还不错,我从C/C ++/C#领域来到python,犯了同样的错误,一开始它也使我感到困惑.
Don't feel bad, I came to python from a C/C++/C# world, made this same mistake, and it confused me too at first.
这篇关于班级中的怪异名单行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!