instance puzzle

Alexander Schmolck a.schmolck at gmx.net
Fri Oct 10 20:18:21 EDT 2003


"kaswoj" <kaswoj at gmx.net> writes:

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

Yep, I should think so; short explanation follows (It's late so clarity and
accuracy might suffer).



> -- Dominik
> 
> class MyClass:

# these two are *class* variables shared between all instances of the class

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

                  A)               B)

This line looks up self.list twice (A) ,B) ). Since there is no instance
variable self.list, it resorts to the class variable MyClass.list. Then it
*mutates* it with append.

>         if self.num == 0: self.num = i

                 C)             D)

This looks up self.num once and again resorts to the class variable ( C) ).
However assignment to self.XXX creates a new *binding* of a value to an
instance attribute name (even if there already is a class variable of the same
name). (Try adding the line ``print MyClass.num, self.num, MyClass.list,
self.list``)

I suspect what you want is:

class MyClass:
    def __init__(self):
        # run each time instance is created; viz. we create instance variables
        self.num = 0
        self.list = []
   

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



'as




More information about the Python-list mailing list