Setting Class Attributes

the.theorist the.theorist at gmail.com
Tue Oct 25 14:09:34 EDT 2005


I have a small, simple class which contains a dictionary (and some
other stuff, not shown). I then have a container class (Big) that holds
some instances of the simple class. When I try to edit the elements of
the dictionary, all instances obtain those changes; I want each
instance to hold separate entries.

#----------Begin module test.py
class ex:
    def __init__(self, val={}):
        self.value = val
    def __str__(self):
        return str(self.value)

class Big:
    def __init__(self):
        self.A = ex()
        self.B = ex()
    def __str__(self)
        return "A=%s, B=%s"%(self.A, self.B)
    def changea(self):
        a = self.A.value
        a['x'] = 1
        a['y'] = 10

print "x = Big()"
x = Big()
print x

print "x.changea()"
x.changea()
print x

print "x.B.value = 30"
x.B.value = 30
print x
#----------End module test.py

#----------Begin actual output
x = Big()
A={}, B={}
x.changea()
A={'x':1, 'y':10}, B={'x':1, 'y':10}
x.B.value = 30
A={'x':1, 'y':10}, B=30
#----------End actual output

#----------Begin Desired output
x = Big()
A={}, B={}
x.changea()
A={'x':1, 'y':10}, B={}
x.B.value = 30
A={'x':1, 'y':10}, B=30
#----------End Desired output

I'm never actually planning on changing the dictionary into something
else, I just included that test to see wether both A and B would be set
to 30. I'm clearly missing something here: Why do both dictionaries
appear to get the same data when they are clearly separate instances?




More information about the Python-list mailing list