Inexplicable behavior in simple example of a set in a class

Chris Rebert clp2 at rebertia.com
Sat Jul 2 18:14:02 EDT 2011


On Sat, Jul 2, 2011 at 2:59 PM, Saqib Ali <saqib.ali.75 at gmail.com> wrote:
<snip>
> Then I instantiate 2 instances of myClass2 (c & d). I then change the
> value of c.mySet. Bizarrely changing the value of c.mySet also affects
> the value of d.mySet which I haven't touched at all!?!?! Can someone
> explain this very strange behavior to me? I can't understand it for
> the life of me.
<snip>
> class myClass2:
>
>    mySet = sets.Set(range(1,10))
>
>    def clearSet(self):
>        self.mySet.clear()
>
>    def __str__(self):
>          return str(len(self.mySet))

Please read a tutorial on object-oriented programming in Python. The
official one is pretty good:
http://docs.python.org/tutorial/classes.html
If you do, you'll find out that your class (as written) has mySet as a
class (Java lingo: static) variable, *not* an instance variable; thus,
it is shared by all instances of the class, and hence the behavior you
observed. Instance variables are properly created in the __init__()
initializer method, *not* directly in the class body.

Your class would be correctly rewritten as:

class MyClass2(object):
    def __init__(self):
        self.mySet = sets.Set(range(1,10))

    def clearSet(self):
# ...rest same as before...

Cheers,
Chris
--
http://rebertia.com



More information about the Python-list mailing list