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()
and then call addToList on ver1:
ver1.addToList(3)
and then output ver2’s list:
ver2.outputList()
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:
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:
You need to declare regular “member variables” in the
__init__constructor.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.