[Tutor] Problems with references

Alan Gauld alan.gauld at blueyonder.co.uk
Wed Jun 2 03:14:45 EDT 2004

> I have several objects, which use the same class definition.

I assume you mean they are all instances of the same class?
Not that they have a reference to the class?

> class definition, there is an attribute of the type dictionary.
> I would expect that the dictionary attribute will not be the same
> accross the objects.

If the dictionary is defined as a class attribute it will be
shared across instances. That is what class attributes are for.
If you want it to be per instance you need to define it within
the __init__ method.

If OTOH you are holding a reference to the class within other
objects then again the objects will all point at the same
class object and share the dictionarey.

All three scenarios are illustrated below:

class C:
   sharedDict = {}   # class attribute shared by all instances
   def __init__(self):
       self.uniqueDict = {}  # this is unique per insance
   def printDicts(self)
       print self.sharedDict
       print self.uniqueDict

class D:
   def __init__(self):
       self.c_ref = C  # reference to the class
   def printDict:
       print self.c_ref.sharedDict

c = C()
d = C()

c.sharedDict[1] = 'one'
c.uniqueDict[1] = 'ONE'
d.sharedDict[1] = 'CHANGED IT!"
d.uniqueDict[1] = "WON"

e = D()

> Here is an sample of when i put the references into the
>     def examineParticipations(self):
>         for id, participation in self.Participations.iteritems():
>             # lets first figure out what type it is
>             connection1ObjectType =
> self.findDiaObject(participation.connection1)
>             connection2ObjectType =
> self.findDiaObject(participation.connection2)
>             # attr
>             if connection1ObjectType == "attribute":
>                 connection1Object =
> self.Attributes[participation.connection1]
>                 # attr

Off topic, but looking at this code I can't help thinking it
doesn't look very object like... Couldn't the connectionObjects
themselves figure out what to do? Rather than have a 'if type==XXX'
statement? Such statements are very rarely needed in OO designs
and are a common maintenance headache in the future. On of the
big bendefits of OO is to avoid those types of if statements.

But without more understanding of what the various objects do
I can't be sure, so maybe you do need to do it that way.

> Why is a references added into one dictionary attribute also added
> all other dictionary attributes, in objects of teh the same class
> definition, when one would expect that they where different

Hopefully my example above has demonstrated that - assuming that
my guess is right and you have created them as class attributes.


Alan G
Author of the Learn to Program web tutor

More information about the Tutor mailing list