[Tutor] references to containing objects

Alan Gauld alan.gauld at btinternet.com
Mon Jun 23 10:29:00 CEST 2008


"John Gunderman" <meanburrito920 at yahoo.com> wrote

>I am looking for a way to tell a object the properties of its 
>containing object.

Can you explain why. Thats usually a bad idea.
At the very least it should call a method of the containing
object rather than "access its properties" (assuming you
mean its data)

> What I want is for the object "foo" to be able to access
> properties of container_object through its action() method.

The normal way to do this is to pass a "parent" argument
to the constructor or in a method at assignment:

class Container:
    def __init__(self)
        self.objects = []
    def add(self, item)
        self.objects.append(item)

class Contained:
    def __init__(self.parent = None):
         self.parent = parent
         parent.add(self)
    def setParent(self,parent):
         self.parent = parent
         parent.add(self)
    def action(self):
         self.parent.doSomething()
         # do stuff here

box = Container()
bag = Container()

item = Contained(box)
irtem2 = Contained(bag)

item3 = Contained()
item3.setParent(box)


> the problem is that I don't know what the containing
> object's name is going to be before hand,

I assume you know at the point of assignment?
In which case the addParent would work.


> I'm thinking I could create a dict of the container_objects, so
> when the object was created the name could be passed
> to the action() method,

The whole problem with this technique (and with the idea
of accessing the container properties) is that it breaks the
concept of data hiding and self containment.
Objects should be loosely coupled - ie know very little
about each other except the public interface(ie the methods)
and tightly coherent - ie should be the only entity operating
on their internal data. Any time one object has to access
the innards of another object, or has to access an external
data source to perform an internal action its a warning sign.
Not necessarily an error just a warning that something
may be wrong withthe design. A bad smell if you like.

HTH,

-- 
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld 




More information about the Tutor mailing list