Polymorphism means “one call, object-specific behavior.” Caller code writes employee.get_salary() once: a full-time employee adds salary and bonus, while a part-time employee multiplies wage by hours. The loop avoids a pile of type checks because each object owns its calculation.
When objects share a parent, the common method acts as an explicit contract. Python also supports duck typing: unrelated classes can participate as long as they provide the methods caller code needs.
Same method name, different implementations
class Employee:
def get_salary(self):
raise NotImplementedError
class FullTimeEmployee(Employee):
def __init__(self, name, salary, bonus):
self.name, self.salary, self.bonus = name, salary, bonus
def get_salary(self):
return self.salary + self.bonus
class PartTimeEmployee(Employee):
def __init__(self, name, wage, hours):
self.name, self.wage, self.hours = name, wage, hours
def get_salary(self):
return self.wage * self.hours
employees = [FullTimeEmployee("Alice", 5783, 173),
PartTimeEmployee("Bob", 150, 15)]
for employee in employees:
print(employee.get_salary())Polymorphic payroll: one loop, different calculations
Unlock the complete interactive lab, deeper explanations, and curated reference answers.
KNOWLEDGE QUIZ
KNOWLEDGE QUIZ
Duck typing and extensibility
Report, Invoice, and GradeSheet are not necessarily the same kind of thing, but each may provide export(). export_all() depends only on that behavior. A future Receipt can join without changing the loop if it also implements export. The tradeoff is that a missing method fails at the call site, so naming conventions, tests, and clear documentation matter.
Duck typing asks what an object can do, not only what it inherits from.
def export_all(items):
for item in items:
print(item.export())KNOWLEDGE QUIZ
KNOWLEDGE QUIZ
Calculate different salaries in one loop
- Implement FullTimeEmployee and PartTimeEmployee.
- Both provide get_name() and get_salary().
- Put them in one list and print names and salaries with one loop.
Batch export with duck typing
- Create unrelated Report, Invoice, and GradeSheet classes.
- Each implements export() and returns distinct text.
- Write export_all(items) using only item.export().
- Add Receipt and prove export_all needs no changes.