0

I was looking at a code which a Parent class calls super:

class ParentClass:
    def __init__(self):
        super(ParentClass, self).__init__()

I don't understand why would someone call super on itself and how does this not get stuck on a recursive loop. Is there something in the background of Python mechanisms that I'm missing?

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
user10728141
  • 59
  • 1
  • 8
  • 2
    Can you clarify what you mean by "call super on itself", or what you do not understand about this? The entire point of ``super`` is to find the parent class *of the current class*, so it needs to know the current class (what you likely mean by "itself"). Note that Python3 allows parameter-free ``super()`` calls in most cases. – MisterMiyagi Jul 15 '20 at 10:53
  • The first argument to `super` is the class to start looking *from*. In a simple case this would resolve to `object.__init__`, but allows this class to cooperate in a multiple-inheritance case. – jonrsharpe Jul 15 '20 at 10:53
  • The way I see it: We have entered already `__init__` adn we are calling super which does not have an upper level to go since we are in the base class, why does this work? I thought when we are at the parent, super would point again to the parent which is not the case. Can someone explain what is happening behind the scenes in this case since I can't find any information about using super inside parent class (it does not have any other level up) – user10728141 Jul 15 '20 at 10:57
  • Visit Here for explanation: https://stackoverflow.com/questions/576169/understanding-python-super-with-init-methods – ErfanFi79 Jul 15 '20 at 10:58
  • I;ve seen that but super is used in base class this time, this is the confusing part as for me it's unpredicted behavior – user10728141 Jul 15 '20 at 10:59

1 Answers1

3

In python, all classes are implicitly a subclass of object. super will always follow a Method Resolution Order (mro) to determine which function to call. This is explained well in the super docs.

So, for a class like-

class ParentClass:
    def __init__(self):
        super(ParentClass, self).__init__()

The mro follows - ParentClass -> object

Which means super(ParentClass, self) (or the shorthand, super()) translates to object and object.__init__() is indeed a very valid call.

Chase
  • 5,315
  • 2
  • 15
  • 41
  • Aren't Base classes inheriting already everything from `object` type? What is the benefit of calling `object.__init__()` ? – user10728141 Jul 15 '20 at 11:02
  • 2
    There is no *real* benefit. It's simply a way to be **consistent** with the subclasses. i.e if every class is calling a super init, it's more consistent @user10728141 – Chase Jul 15 '20 at 11:05
  • Thank you, that really covers my question! As for consistency: It feels that doing this on the *base* class breaks a Python "zen" thing. But all in all, this does not have any hidden mechanisms called behind it, that's what I'll keep. – user10728141 Jul 15 '20 at 11:08