Class instance problem?

Miki Tebeka miki.tebeka at zoran.com
Thu May 13 02:04:29 EDT 2004


Hello Zhao,

> class aclass:
>     num = 0
>     l = [[],[]]
> 
> a = aclass()
> b = aclass()
> a.l.append(1)
> print "a.l",a.l
> print "b.l",b.l
> 
>   My expectation is that a,b are separate objects, but appending to
> a's l also appends to b's l. Why does this occur? On the other hand,
> the command
> 
> a.num = 1
> 
> doesn't change b.num's. This is inconsistency is driving me crazy.
> What am I doing wrong?
Several things :-)
First, "num" and "l" are both *class* properties and not object 
properties. The right way to do this is:
class aclass:
     def __init__(self):
         num = 0
         l = [[], []]

Each class method has a `self' parameter which is the object that is 
currently called. See the tutorial for more explanation on the subject.

Second "num" and "l" are named bounded to the same objects objects both 
in a and b. When you do `a.num =1' you change the binding of a.num to 1. 
When you do a.l.append you append to the same objects as in b.l.

HTH.
Miki



More information about the Python-list mailing list