Referencing a container object's attributes

Tim Churches tchur at optushome.com.au
Sat Mar 24 21:44:47 EST 2001


Brian Quinlan wrote:
> 
> I gather that you are describing a situation similar to the following:
> 
> class a:
>         def doSomething(self):
>                 # I need to access the "b" instance that instantiated me here!
> 
> class b:
>         __init__(self):
>                 self.a = a()
>                 self.a.doSomething( )
> 

Yes, precisely.

> Is so, there there is no language feature that would allow you to do
> this without passing an instance of 'b' to 'a'. Standard practice would
> be to do something like this:
> 
> class a:
>         def __init__(self, parent):
>                 self.parent = parent
> 
>         def doSomething(self):
>                 self.parent.blah( )
> class b:
>         __init__(self):
>                 self.a = a( self )
> 

OK, many thanks. 

One question: does the circularity inherent in the above (in which a
reference to the container object is placed in an attribute of each
containee) have any potential for causing problems - particularly since
I want to pickle the container objects?

Cheers,

Tim C


> On Saturday, March 24, 2001, at 06:15 PM, Tim Churches wrote:
> 
> > Is there any way for a method of a class instance which is embedded in a
> > container class instance to look up attributes of that container class
> > instance (i.e. the one which contains it)? At the moment I am putting
> > the name of the container instance in an attribute of the containee (at
> > the time when the containee is instantiated). Is there a neater way? All
> > the Python texts cover referencing an object's superclass(es), but not
> > its container object(s).
> >
> > Tim C
> >
> > --
> > http://mail.python.org/mailman/listinfo/python-list
> >




More information about the Python-list mailing list