Derived classes allow code reuse this make code more easy to mantain and help in avoiding codding errors. However in derived class appear often casses when inherited method from parrent class isn't appropriate.
For example let's presume we have an Employee class which have 3 attributes name, salary, phone and a method printEmployee which will display employee name and phone.
We derive from this a class Freelancer which have in plus atttribute domain. We need that for freelacer, printEmployee method to print name, phone and in plus domain. In this case printEmployee from base class is not apropriate and we need to extend it. Below is sample code:
class Employee:
def __init__(self,nameValue, salaryValue, phoneValue):
self.name=nameValue
self.salary=salaryValue
self.phone=phoneValue
def getName(self):
return self.name
def getSalary(self):
return self.salary
def printEmployee(self):
print(f"Employee: {self.name} have phone {self.phone}")
class Freelancer(Employee):
def __init__(self,nameValue, salaryValue, phoneValue, domainValue):
super().__init__(nameValue, salaryValue, phoneValue)
self.domain=domainValue
def printEmployee(self):
print(f"Freelancer: {self.name} have phone {self.phone} and works in domain {self.domain}")
#create Employee object and use it printEmployee
emp1=Employee('Jd',4000,'555-342345')
emp1.printEmployee()
#create Freelancer object and use it overriding printEmployee method
fr1=Freelancer("TomH", 4200,'555-346534', 'Graphic design')
fr1.printEmployee()
#output:
Employee: Jd have phone 555-342345
Freelancer: TomH have phone 555-346534 and works in domain Graphic design