Accessing container's methods

Ian Kelly ian.g.kelly at gmail.com
Mon Dec 7 14:33:41 EST 2015


On Mon, Dec 7, 2015 at 11:10 AM, Tony van der Hoff <tony at vanderhoff.org> wrote:
> Hi,
>
> I have a class A, containing embedded embedded classes, which need to access
> methods from A.
> .
> A highly contrived example, where I'm setting up an outer class in a Has-a
> relationship, containing a number of Actors. The inner class needs to access
> a method of the outer class; here the method get_name.
>
> I don't really want to make Actor a sub-class (is-a; it isn't) of Monty;
> that would raise all sorts of other problems.
>
> Can anyone please advise me on how to achieve this magic?

I'm guessing that you're coming from Java. Java has two different
types of nested classes: non-static, where an instance of the inner
class is implicitly associated with an instance of the outer class;
and static, where an instance of the inner class is unrelated to any
instance of the outer class.

It looks like you're trying to do the former, but Python only has the
static type of nested classes. So how would you go about creating a
nested class of the non-static type? Make the association explicit.
When Monty creates an Actor, pass it self as one of the arguments.
Actor can then save that instance of Monty in an attribute and call
the method thusly.

As others have noted, this does create a reference cycle. The Python
garbage collector is fine with cleaning up reference cycles as long as
there are no objects __del__ methods anywhere in the cycle, so it's up
to you whether you consider that to be a problem or not.



More information about the Python-list mailing list