Search code examples
pythonclassinner-classes

How to call variable of the upper class in inner class?


I have to call a variable defined at the upper class to the inner class.

Code

class outer:
  def __init__(self):
    self.Out = 'out'
    self.In = self.inner()
  class inner:
    def __init__(self):
      self.InOut = outer.Out

c = outer()

Error message

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 4, in __init__
  File "<stdin>", line 7, in __init__
AttributeError: type object 'outer' has no attribute 'Out'

Solution

    • To create a new instance of the Inner class, you should prepend with the Outer class name, i.e Outer.Inner().
    • You should define the Inner class before referencing it.
    • in Outer.__init__, you can pass the container object into the created instance of Inner class, i.e Outer.Inner(self), which will be passed as argument outer in Inner.__init__ method.
    class Outer:
      class Inner:
        def __init__(self, outer):
          self.in_out = outer._out
          print(self.in_out)
    
      def __init__(self):
        self._out = 'out'
        self._in = Outer.Inner(self)
    
    c = Outer()