instance puzzle
Mark Day
mday at apple.com
Fri Oct 10 20:15:48 EDT 2003
In article <3f874026$1 at pfaff2.ethz.ch>, kaswoj <kaswoj at gmx.net> wrote:
> 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
[snip]
> Program output I would expect:
> [0]
> 0
> [1]
> 1
> [2]
> 2
> [3]
> 3
Try removing the "if self.list == []: " from setVar, and you'll get
this output:
[0]
0
[0]
1
[0]
2
[0]
3
[0]
0
[0, 1]
1
[0, 1, 2]
2
[0, 1, 2, 3]
3
I think your confusion comes from the fact that num and list class
variables (is that the right term?), not instance variables. That is,
there is only one "num" or "list", shared by all instances of MyClass.
The first object gets created and appends 0 to the list. After that,
the list is not empty, so nothing else is appended (and the list
remains [0]).
To get the output you expected, change the class definition to:
class MyClass:
def __init__(self):
self.num = 0
self.list = []
def setVar(self, i):
self.list.append(i)
if self.num == 0: self.num = i
-Mark
More information about the Python-list
mailing list