Exploring Polymorphism in Python: A Guide to Flexible and Reusable Code
☰Fullscreen
Table of Content:
Polymorphismallows a subclass to override or change a specific behavior, exhibited by the parent class
Polymorphism Example
In the below shown example, you will find
-
Improvised
Employeeclass with two methodsgetSalaryandgetBonus. -
Definition of
ContractEmployeeclass derived fromEmployee. It overrides functionality ofgetSalaryandgetBonusmethods found in it's parent classEmployee.
Example
class Employee(Person): all_employees = EmployeesList () def __init__(self, fname, lname, empid): Person.__init__(self, fname, lname) self.empid = empid Employee.all_employees.append(self) def getSalary(self): return 'You get Monthly salary.' def getBonus(self): return 'You are eligible for Bonus.'
Polymoprhism Example Contd.
class ContractEmployee(Employee): def getSalary(self): return 'You will not get Salary from Organization.' def getBonus(self): return 'You are not eligible for Bonus.' e1 = Employee('Jack', 'simmons', 456342) e2 = ContractEmployee('John', 'williams', 123656) print(e1.getBonus()) print(e2.getBonus())
Output
You are eligible for Bonus. You are not eligible for Bonus.