[Tutor] Inner Class access to outer class attributes?

Danny Yoo dyoo at hkn.eecs.berkeley.edu
Thu Mar 23 22:58:17 CET 2006



On Thu, 23 Mar 2006, stv wrote:

> Hmmm, so every Sublocation object has a copy of the grouplocation data?

Hi stv,

Not exactly: each sublocation has a "reference" to the parent
grouplocation.  There's a distinction between a "reference" and a copy.
Think of a reference as an arrow to the other thing.  For example:

#########################################################
class Person:
    def __init__(self, name):
        self.name = name
        self.friends = []

    def befriend(self, other):
        self.friends.append(other)
        other.friends.append(self)

    def greet(self):
        print "hi, I'm", self.name, "and my friends are:",
        for friend in self.friends:
            print friend.name,
        print
#########################################################

If we have three people, say, larry, curly, and moe:

######
>>> larry, curly, moe = Person("Larry"), Person("Curly"), Person("Moe")
######

then befriending between any two people doesn't "copy" anyone: it's just
lets them know about each other.

######
>>> larry.befriend(curly)
>>> curly.befriend(moe)
>>> curly.greet()
hi, I'm Curly and my friends are: Larry Moe
######


If we later change the name of someone like moe:

######
>>> moe.name = 'moe the burninator'
######

then if curly starts greeting people again, we see that curly now refers
to moe as 'moe the burninator':

######
>>> curly.greet()
hi, I'm Curly and my friends are: Larry moe the burninator
######


So Curly has a list of references to friends.  A model diagram of the
situation looks something like this:


larry --------------> { name,    friends  }
                         |          |
                         V          |
                      "Larry"       [ x, x ]
                                      |  |
                                      |  |
curly --------------> { name, ...} <-/   |
                         |              /
                         V             /
                      "Curly"         /
                                     /
moe ----------------> { ... } <------


where I'm just using some ad-hoc notation to show that the names we use
are arrows to thingy's that I've put in brackets.  And if we look at the
friends of Larry, we'll see that each element in friends is actually a
reference to the thingy's that represent Curly and Moe.

If Curly had "copied"  Moe rather than "refered" to Moe, we'd see
different results.  Does this make sense?



More information about the Tutor mailing list