[Tutor] Inner Class access to outer class attributes?

Kent Johnson kent37 at tds.net
Thu Mar 23 21:36:31 CET 2006


stv wrote:
> # So I figure out inner classes while typing the
> # first draft of this email, at least mostly
> # How do I access the "outer" class attributes from
> # the inner class?

Unlike Java (for example), in Python an inner class doesn't have any 
special access to attributes of an instance of an enclosing class. They 
are more like Java's static nested classes.

If you want access to a GroupLocation instance, just pass it to the 
sublocation.
> 
> class GroupLocation(list):     ### Note subclass of list
> 
>   class _Sublocation(object):
>     def __init__(self, sublocation, action):
>       self.sublocation = sublocation
>       self.action = action

     def __init__(self, grouplocation, sublocation, action):
       self.grouplocation = grouplocation
       self.sublocation = sublocation
       self.action = action

>     def do_stuff(self):
>       ###
>       ### How would I get to GroupLocation attributes?
>       ###
>       print GroupLocation.name, self.sublocation

       print self.grouplocation.name, self.sublocation

Kent



More information about the Tutor mailing list