Accessing container's methods
Terry Reedy
tjreedy at udel.edu
Mon Dec 7 16:38:33 EST 2015
On 12/7/2015 1:10 PM, Tony van der Hoff 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?
>
> # define the outer class
> class Monty:
> def __init__( self, names ):
> self.actors = []
>
> i = 0
> for n in names:
> self.actors.append( Actor( n, i ) )
> i += 1 # here is a case for python supporting post-increment!
This is actually a case for using enumerate:
for i, name in enumerate(names):
>
> def count_actors( self ):
> return len( self.actors )
>
> def list_actors( self ):
> h=[]
> for n in self.actors:
> h.append( n.get_name() )
> return h
return list(self.actors) # or perhaps even faster
return self.actors[:]
> # define the inner class
> class Actor:
> def __init__ ( self, name, id ):
> self.name = name
> self.id = id
Tkinter, and I presume tk, works by creating circular references.
widgets get a reference to a master widget, and container get a
reference to widgets that are placed (or packed or gridded) therein.
Widgets have an explicit .destroy method (inherited from tcl/tk) to undo
the circularity. It works, but it is not completely without problems.
--
Terry Jan Reedy
More information about the Python-list
mailing list