Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fundamentals of inheritance in Python

I am trying to understand how inheritance works in python. I was looking at a simple code and one thing is confusing me. The code is following:

class Person:

    def __init__(self, first, last):
        self.firstname = first
        self.lastname = last

    def Name(self):
        return self.firstname + " " + self.lastname

class Employee(Person):

    def __init__(self, first, last, staffnum):
        Person.__init__(self,first, last)
        self.staffnumber = staffnum

    def GetEmployee(self):
        return self.Name() + ", " +  self.staffnumber

x = Person("Marge", "Simpson")
y = Employee("Homer", "Simpson","1007")
print(x.Name()) 
print(y.GetEmployee())

My question is that when are using Person.__init__() to call the constructor of baseclass but when we calling Name() method of base class again, instead of using "Person", we are using "self". Can somebody clear this confusion and me understand the how inheritance works in python?

like image 806
Shahroz Punjwani Avatar asked Mar 16 '26 07:03

Shahroz Punjwani


1 Answers

The Employee class inherits methods from the base Person class, including the __init__ method. So at the top of the class definition, it has __init__ and Name methods.

Then the Employee class definition overwrites the __init__ method that it inherited. In order to call the __init__ method of Person, it has to call Person.__init__ by name (actually, it could use super() as another alternative).

But since Employee doesn't overwrite the inherited Name method, it can use self.Name() to call the Name method that it inherited at the top.

like image 105
user2034412 Avatar answered Mar 18 '26 19:03

user2034412