3

Why don't we need self reference when we use super().__init__?(such as line 9 down below)

class labourers():
    def __init__(self,name,department,salary):
        self.name = name
        self.department = department
        self.salary = salary

class managers(labourers):
    def __init__(self,name,department,salary,numberofpeople):
        super().__init__(name,department,salary)
        self.numberofpeople = numberofpeople

ShadowRanger
  • 143,180
  • 12
  • 188
  • 271
ersanowski
  • 59
  • 6
  • 1
    For the same reason you don't have to pass `self` when you call other methods. – Mark Apr 16 '20 at 23:53
  • 2
    @MarkMeyer. Not exactly. Super is special. – Mad Physicist Apr 16 '20 at 23:54
  • 1
    @MarkMeyer But you do have to write `self.method(...)`. `super` uses some magic to avoid having to specify `self`. – interjay Apr 16 '20 at 23:54
  • In Python 2 you had to write `super(managers, self)`. It was changed in Python 3 to make this automatic. – Barmar Apr 16 '20 at 23:56
  • 1
    @interjay I took the question to be asking why you don't need `super().__init__(self, name,department,salary)` The answer is that, like method calls, python does it for you. – Mark Apr 16 '20 at 23:56

1 Answers1

4

Super's functionality in this case is implemented in the CPython parser. See PEP 3135

Replacing the old usage of super, calls to the next class in the MRO (method resolution order) can be made without explicitly passing the class object (although doing so will still be supported). Every function will have a cell named __class__ that contains the class object that the function is defined in.

The new syntax:

super()

is equivalent to:

super(__class__, <firstarg>)

[...]

While super is not a reserved word, the parser recognizes the use of super in a method definition and only passes in the __class__ cell when this is found. Thus, calling a global alias of super without arguments will not necessarily work.

Emphasis added.

Mad Physicist
  • 107,652
  • 25
  • 181
  • 264
sytech
  • 29,298
  • 3
  • 45
  • 86