Inexplicable behavior in simple example of a set in a class

Saqib Ali saqib.ali.75 at gmail.com
Sat Jul 2 17:59:51 EDT 2011



I have written two EXTREMELY simple python classes. One class
(myClass1) contains a data attribute (myNum) that contains an integer.
The other class (myClass2) contains a data attribute (mySet) that
contains a set.

I instantiate 2 instances of myClass1 (a & b). I then change the value
of a.myNum. It works as expected.

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.

Please see below the source code as well as the output.


-------------------------- SOURCE CODE ------------------------------
import sets

class myClass1:

    myNum = 9

    def clearNum(self):
        self.myNum = 0

    def __str__(self):
          return str(self.myNum)

class myClass2:

    mySet = sets.Set(range(1,10))

    def clearSet(self):
        self.mySet.clear()

    def __str__(self):
          return str(len(self.mySet))

if __name__ == "__main__":

    # Experiment 1. Modifying values of member integers in two
different instances of a class
    # Works as expected.
    a = myClass1()
    b = myClass1()
    print "a = %s" % str(a)
    print "b = %s" % str(b)
    print "a.clearNum()"
    a.clearNum()
    print "a = %s" % str(a)
    print "b = %s\n\n\n" % str(b)



    # Experiment 2. Modifying values of member sets in two different
instances of a class
    # Fails Unexplicably. d is not being modified. Yet calling
c.clearSet() seems to change d.mySet's value
    c = myClass2()
    d = myClass2()
    print "c = %s" % str(c)
    print "d = %s" % str(d)
    print "c.clearSet()"
    c.clearSet()
    print "c = %s" % str(c)
    print "d = %s" % str(d)




-------------------------- OUTPUT ------------------------------
> python.exe myProg.py

a = 9
b = 9
a.clearNum()
a = 0
b = 9



c = 9
d = 9
c.clearSet()
c = 0
d = 0



More information about the Python-list mailing list