Newby Q: nested classes, access of upper method

Nick Coghlan ncoghlan at
Sat Dec 4 09:59:53 CET 2004

Gregor Horvath wrote:
> Hello,
> class A(self):
>   def A1():
>     pass
>     class B(self):
>       def B1():
>     #************************************
>         #***  How can I access A1 here???? ***
>     #************************************
>     self.A1() # doesnet work because self references to  B
>     self.self.A1() #doesnt work either
> Renanimg class B(self1): doesnt work either because self is not bound.

OK, I suspect you're a little confused about how classes work. The items in 
brackets after a class name are the *base* classes of a class, not the way the 
class refers to itself. So Python will complain if the listed items can't be 
inherited from for one reason or another.

I suggest having another read of the tutorial section on classes to figure out 
exactly what you want to be doing:

> How can I access a method of a "upper" class?

Merely defining one class inside another class does not automatically give 
instances of that inner class a reference to an instance of the outer class - if 
such a reference is needed, it must be provided in the inner class's constructor.


class A(object):
   class B(object):
     def __init__(self, owner):
       self._owner = owner

     def B1(self):

   def A1(self):

   def makeB(self):
     return A.B(self)


More information about the Python-list mailing list