'parent object'?

Quinn Dunkan quinn at retch.ugcs.caltech.edu
Tue Jun 25 23:33:26 CEST 2002

On Tue, 25 Jun 2002 13:59:03 -0400, laotseu <bdesth at nospam.free.fr> wrote:
>That's ok for 'parent/child' in the inheritence meaning. But the OP 
>asked about something else : a container instance (the 'parent'), and 
>the instances it contains (the 'childrens'). This has nothing to do with 
>  subclassing.
><to the op>
>You should define a 'container/child' interface. it may be very simple 
>in Python, something like
>class container:
>     def __init__(self):
>         self.childrens = []
>     def add_child(self, child):
>         if child not in self.childrens:
>             child.parent = self     # create a 'parent' attribute
>             self.childrens.append(child)
>     def remove_child(self, child):
>          if child in self.childrens:
>	    del self.childrens[self.childrens.index(child)]
>             del child.parent
>Now whatever class your child objects is an instance of, it gets a new 
>'parent' attribute when you add it to the container instance, and looses 
>this attribute when you remove it...

This also introduces a cycle.  In older pythons, discarded containers would
never deallocate their children.  In newer pythons, the garbage will get
cleaned eventually.

As a random aside, I've found that almost always when I thought I needed to
have a child know about its parent, it's turned out to be a design mistake.
Cyclical dependency is messy to think about.  Things can wind up getting called
in weird ways, and getting in tricky infinite recursion.

As another random aside, using __getitem__ and __setitem__ is usually more
natural for this kind of thing.

More information about the Python-list mailing list