latentspace.

super()


  • Python super()
    • The super() function is used to give access to methods and properties of a parent or sibling class.
    • The super() function returns an object that represents the parent class.
    • 
          class Foo:
              def __init__(self):
                  self.foo = "foo"
                  
              def _print_self_foo(self):
                  print(self.foo)
      
              def _print_foo(self):
                  print("foo")
      
      
          class Bar(Foo):
              def __init__(self):
                  pass
              
              def print_foo(self):
                  super()._print_foo()
                  self._print_foo()
                  
              def print_self_foo(self):
                  self._print_self_foo()
              
              def print_self_foo_after_inheritance(self):
                  super().__init__()
                  self._print_self_foo()
      
      
          if __name__ == "__main__":
              import traceback
              
              bar = Bar()
              bar.print_foo()
              # > foo
              # > foo
              
              try:
                  bar.print_self_foo()
              except Exception as e:
                  traceback.print_exc()
                  # > AttributeError: 'Bar' object has no attribute 'foo'
              
              bar.print_self_foo_after_inheritance()
              # > foo
      
    • print_self_foo() method of Bar occurs AttributeError because Foo.__init__() method wasn't called
    • super().__init__() is basically called in the child class's __init__()