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

  • 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()