'parent object'?

laotseu bdesth at nospam.free.fr
Tue Jun 25 19:59:03 CEST 2002


Erik Max Francis wrote:
> "Guyon Morée" wrote:
> 
> 
>>Is there, like 'self, also a 'parent' object of some sort?
>>
>>The problem i'm having is that i have a class, which contains a list
>>of
>>instances of another class. How can i let this 'childclass' call a
>>function
>>which is on the 'parent class'?
> 
> 
> An instance has access to its class (.__class__ attribute), and a class
> has access to its parent classes (.__bases__ attribute).
> 

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...

Well... it could be safer to check if the 'child' object already has a 
parent before you add it, but y'll sure improve all this !-)


Hope this helps

laotseu




More information about the Python-list mailing list