Page 411 - Computer_Science_F5
P. 411
Computer Science Implementation of key OOP same name but different parameter
lists. By default, Python does not
features in Python
support method overloading, but
it can be simulated using default
parameter values or variable-length
Polymorphism in Python
FOR ONLINE READING ONLY
Polymorphism in Python enables objects argument lists.
from different classes to be treated as (b) Method overriding: Method
objects of a shared superclass. As explained overriding happens when a subclass
earlier in other languages, polymorphism provides its own implementation of
is achieved through method overloading a method that is already defined in
and method overriding. its superclass. It enables subclasses
to customize the behavior of
(a) Method overloading: Method inherited methods. The following
overloading in Python involves Program example 6.3 demonstrate
defining multiple methods with the polymorphism.
Program example 6.3:
Program code demonstrating polymorphism
class Animal:
def speak(self):
return “Animal speaks”
class Dog(Animal):
def speak(self):
return “Dog barks”
class Cat(Animal):
def speak(self):
return “Cat meows”
# Polymorphic behavior
animals = [Animal(), Dog(), Cat()]
for animal in animals:
print(animal.speak())
Output:
Figure 6.7: Output of polymorphism program code
402
for Advanced Secondary Schools
Computer Science Form 5.indd 402 23/07/2024 12:34

