Accessing container's methods

Thomas 'PointedEars' Lahn PointedEars at web.de
Mon Dec 7 14:03:59 EST 2015


Michael Torrie wrote:

> On 12/07/2015 11:10 AM, Tony van der Hoff wrote:
>> 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?
> 
> You could add an attribute to each embedded object that provides a
> reference back to the container object.

ACK.

> All in all, this design has a kind of smell to it.  Would it not be
> better to ask the container class for information about the children,
> rather than the other way around?  If a piece of code holds a reference
> to the child object then it must also by definition hold a reference to
> the container object, so why can't it ask the container object directly?

Indeed, in this example asking the parent would be the best approach because 
only the number of actors is requested.  That number should not change, and 
if it can change, then there should be an interface for that (a public 
method), in which the parent must update it.  So Monty.count_actors() does 
not have to count the actors each time it is called from Actor.get_name(); 
it just has to return the value of a private attribute containing the 
current count.

In other cases asking the parent would avoid inconsistencies, but that could 
be at the cost of efficiency; for example, a search for each child object, 
which does not scale well.

-- 
PointedEars

Twitter: @PointedEars2
Please do not cc me. / Bitte keine Kopien per E-Mail. 



More information about the Python-list mailing list