Search code examples
pythoninheritancesuper

What do super(MyObject, self).__init__() do in class MyObject __init__() function?


class MyObject1(object):
    def __init__(self):
        super(MyObject1, self).__init__()
        pass

class MyObject2(object):
    def __init__(self, arg):
        super(MyObject2, self).__init__()
        pass

I have read a python27 code like this,

I know 'super' means father class constructor function,

but I cannot understand why these two classes call themselves' constructor function '__init__',

it seems don't have any practical effect.


Solution

  • These are some pretty basic OO methods in Python. Read here.

    super and self are similar:

    super() lets you avoid referring to the base class explicitly, which can be nice. But the main advantage comes with multiple inheritance, where all sorts of fun stuff can happen. See the standard docs on super if you haven't already.

    (from this answer)

    Here's an example of super in action:

    class Animal(object):
         def __init__(self, speed, is_mammal):
              self.speed = speed
              self.is_mammal = is_mammal
    
    class Cat(Animal):
         def __init__(self, is_hungry):
              super().__init__(10, True)
              self.is_hungry = is_hungry
    
    barry = Cat(True)
    print(f"speed: {barry.speed}")
    print(f"is a mammal: {barry.is_mammal}")
    print(f"feed the cat?: {barry.is_hungry}")
    

    You can see that super is calling the base class (the class that the current class inherits), followed by an access modifier, accessing the base class' .__init__() method. It's like self, but for the base class.