instance puzzle

kaswoj kaswoj at gmx.net
Fri Oct 10 19:26:20 EDT 2003


Hello, I have a question concerning python and object instances. In the
sample program below, several instances of the same class are made one after
the other. I would expect that the values of "num" and "list" are reset to
"0" and "[]" with each new instance created. But why the heck does this work
like expected for "num" but not for "list"?!
I'm really stuck and confused. Does anybody know what the problem is?
-- Dominik

class MyClass:
    num = 0
    list = []

    def setVar(self, i):
        if self.list == []: self.list.append(i)
        if self.num == 0: self.num = i

for i in range(0, 4):
    obj = MyClass()
    obj.setVar(i)
    print obj.list
    print obj.num

Program output:
[0]
0
[0]
1
[0]
2
[0]
3

Program output I would expect:
[0]
0
[1]
1
[2]
2
[3]
3






More information about the Python-list mailing list