0% found this document useful (0 votes)
11 views

Polymorphism in Python

Uploaded by

adebusuyisamuel3
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views

Polymorphism in Python

Uploaded by

adebusuyisamuel3
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 1

Polymorphism is a key concept in object-oriented programming that allows objects

of different types to be treated as if they were the same type. In Python,


polymorphism is supported through the use of inheritance and method overriding.

Method overriding is the process of defining a method in a subclass that has the
same name as a method in the superclass. When an object of the subclass is
created, it can be treated as if it were an object of the superclass, and the
overridden method will be called instead of the superclass method.

Here's an example of polymorphism in Python:

ruby
Copy code
class Animal:
def __init__(self, name):
self.name = name

def speak(self):
raise NotImplementedError('Subclass must implement abstract method')

class Dog(Animal):
def speak(self):
return 'Woof!'

class Cat(Animal):
def speak(self):
return 'Meow!'

class Cow(Animal):
def speak(self):
return 'Moo!'

animals = [Dog('Rufus'), Cat('Fluffy'), Cow('Bessie')]

for animal in animals:


print(animal.name + ' says ' + animal.speak())
In this example, we define an abstract Animal class that defines a method called
speak(). This method is marked as abstract using the NotImplementedError
exception, which means that any subclasses of Animal must implement their own
speak() method.

We then define three subclasses of Animal (Dog, Cat, and Cow), each of which
implements its own speak() method.

Finally, we create a list of Animal objects (animals) that includes one instance
of each subclass, and we loop over the list and call the speak() method on each
object. Since each object is an instance of a different subclass, the speak()
method will behave differently for each object, demonstrating the principle of
polymorphism.

In this way, polymorphism allows us to write more flexible and reusable code,
since we can treat objects of different types as if they were the same type,
as long as they implement the same methods.

You might also like