instance puzzle
Terry Reedy
tjreedy at udel.edu
Fri Oct 10 20:39:06 EDT 2003
"kaswoj" <kaswoj at gmx.net> wrote in message
news:3f874026$1 at pfaff2.ethz.ch...
> 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.
As far as I can think, Python never automatically resets anything.
That includes both default parameter values and class attributes used
as default instance attributes.
>But why the heck does this work like expected for "num" but not for
"list"?!
You shadow 'num' and mutate 'list' (which shadows builtin list())
> class MyClass:
> num = 0
> list = []
>
> def setVar(self, i):
> if self.list == []: self.list.append(i)
This executes as "if MyClass.list == []: MyClass.list.append[i]". On
the first call, [] is changed to [0] != [], so that is one and only
trigger and change.
> if self.num == 0: self.num = i
This executes as "if MyClass.num == 0: instance.num=i". Since
MyClass.num remains the same, this always triggers.
> for i in range(0, 4):
> obj = MyClass()
> obj.setVar(i)
> print obj.list # == print MyClass.list == [0]
> print obj.num
>
> Program output:
> [0]
> 0
> [0]
> 1
> [0]
> 2
> [0]
> 3
Exactly as explained.
Terry J. Reedy
More information about the Python-list
mailing list