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?
self.methodto access the superclass implementation only if the subclass doesn't implementmethod. The subclass here implements__init__, so needs to access the superclass version explicitly (although it should do so withsuper), but doesn't implementName. Try changing it and see what happens!super(Employee, self).__init__(first, last). Search for information about bound vs. unbound methods;self.Nameis bound,Person.__init__is unbound.