Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
149 views
in Technique[技术] by (71.8m points)

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

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...