Python – reference inner class from other inner class

This is not possible, since everything you define in a class becomes a valid member only in an instance of that class, unless you define a method with @staticmethod, but there is no such property for a class.

So, this won’t work either:

class Foo(object):
    x = 10

    class A(object):
        pass

    class B(object):
        other = x

This will work, but it is not what you intended:

class Foo(object):
  x = 10

  class A(object):
    pass

  class B(object):
    def __init__(self):
        self.other = Foo.A

f = Foo()
print(f.B().other)

The output is:

<class '__main__.Foo.A'>

The reason this works is that the methods (in this case __init__) are evaluated when the object is created, while assignment before the __init__ are evaluated while the class is read and interpreted.

You can get about the same thing you want by simply define all the classes inside a module of their own. The importing the module, makes it an object whose fields are the classes you define in it.

Leave a Comment