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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With