2
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.

linrongbin
  • 2,967
  • 6
  • 31
  • 59
  • 2
    Try extending a class that actually does something in the initialization, and it will have an effect – OneCricketeer Jul 26 '16 at 09:41
  • 1
    Are those two actual classes you encountered "in the wild" and you are asking why those are using `super`, or is the question about what `super.init` does in general? – tobias_k Jul 26 '16 at 09:43
  • it seems lots of questions been asked before: http://stackoverflow.com/questions/576169/understanding-python-super-with-init-methods and http://stackoverflow.com/questions/222877/how-to-use-super-in-python – linrongbin Jul 26 '16 at 09:50

1 Answers1

5

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.

Omar AlSuwaidi
  • 1,187
  • 2
  • 6
  • 26
Nick Bull
  • 9,518
  • 6
  • 36
  • 58