Search code examples
pythoninheritance

About inheritance in python, why don't people write 'self' in child class?


Here is an example.

class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def get_name(self):
        print('My name is %s.'%self.name)
    
    def get_age(self):
        print('I am %d years old.'%self.age)

class Student(Person):
    def __init__(self, name, age, GPA):
        super().__init__(name, age)
        self.GPA = GPA

    def get_GPA(self):
        print('My grade is %f.'%self.GPA)

Here comes up my curiosity.

When I create Student class, isn't it allowed to code super().__init__(self, name, age)?

If not, what is the precise reason why 'self' should not added to super().__init__(name, age)?


Solution

  • Maybe the best answer is an analogy: if you were to call the get_PGA method of a student instance, you wouldn't do it like:

    student.get_PGA(student)
    

    Instead you would just do student.get_PGA(). The "self" would be passed in implicitly.

    Similarly, if you were calling it from within another method you wouldn't call it like:

    class Student(Person):
    
        def foo(self):
            pga = self.get_PGA(self)
    
    

    You would just use self.get_PGA() instead.

    When calling a method, the first positional argument is implicit. It's the same story with Student.__init__, which is just a method, here the proxy instance returned by super() is passed in as the "self" implicitly.