Vaibhav
Vaibhav

Reputation: 215

Calling a Parent class constructor with super() vs using Parent class name

Why is it so that when I try to call the Parent class constructor using super(), I don't need to pass 'self' as an argument:

super().__init__(x,y)

Yet when I call it using the Parent class itself (named Parent in this case), a 'self' argument needs to be passed.

Parent.__init__(self,x,y)

(x and y are Parent class attributes here)

Just want to understand the background logic here. Thanks!

Upvotes: 3

Views: 93

Answers (1)

Mike Williamson
Mike Williamson

Reputation: 3198

This is because super() can only be called inside a class method definition (like in __init__), and it always refers to itself. Therefore, there is no need, it is redundant.

Interesting you mention it: self used to be required just a few years ago (maybe 5... I cannot remember).


Think of it like calling methods. If I have the following class:

class Conversation:
  def __init__(self):
    pass
  def hi(self, name):
    print(f'How are you doing, {name}?')

convo = Conversation()
convo.hi('Jason')

(output): 'How are you doing, Jason?'

I did not have to specify self when calling convo.hi, I only had to pass an argument to name. Why? Because self is always needed, and therefore redundant.

Same idea with super(). :)


Upvotes: 4

Related Questions