Class instance problem?
David Eppstein
eppstein at ics.uci.edu
Thu May 13 00:53:57 EDT 2004
In article <c0c22f25.0405122043.2f11549d at posting.google.com>,
zhuang at princeton.edu (Zhao Huang) wrote:
> I'm new to python and I've come across a problem with my objects
> corrupting each other.
>
> 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?
When you set num and l in the class body, you're making them class-wide
variables (like static in Java). If you want a different one per
object, you need to set them in the __init__ method.
--
David Eppstein http://www.ics.uci.edu/~eppstein/
Univ. of California, Irvine, School of Information & Computer Science
More information about the Python-list
mailing list