What is the reason why class variables in nested classes are not allowed in python?

Viewed 103

Can't seem to be able to define a class level variable in a nested subclass, such as:

class Outer:
    def __init__(self):
        self.inner_object=self.Inner() 

    class Inner:
        static_variable = 0
        def __init__(self):
            Inner.static_variable = 1

I get an error stating that "Inner is not defined" in that last line of code.

2 Answers

class statements are tricky. They create a new temporary namespace, but do not define a new scope. Since Inner is not defined inside __init__, the name must be looked up in an enclosing scope when __init__ is called and a value for Inner is needed. But the next enclosing scope is not the body of the class statement, so no definition of Inner is found.

The right way to reference the Inner class is by correctly treating it as an attribute of the Outer class.

class Outer:
   def __init__(self):
      self.inner_object = Outer.Inner()

   class Inner:
      static_variable = 0
      def __init__(self):
          Outer.Inner.static_variable = 1

That said, inner classes are very rarely defined in Python, because unlike in Java, there is no prohibition on defining more than one class at the top level of a module.

  • try this
  • use self.Inner()
class Outer:
    def __init__(self):
        self.inner_object=self.Inner()

    class Inner:
        static_variable = 0
        def __init__(self):
            Inner.static_variable = 1
Related