What is polymorphism in Python OOP?

What is polymorphism in Python OOP?

a) The ability to define a single interface for multiple data types
b) Inheritance from multiple base classes
c) The ability to create multiple instances of a class
d) The ability to define a class with no methods

Answer:

a) The ability to define a single interface for multiple data types

Explanation:

Polymorphism in Python OOP refers to the ability to define a single interface or method that can be used by objects of different classes. It allows different classes to be treated as instances of the same class through a common interface, enabling code reuse and flexibility.

class Cat:
def speak(self):
return "Meow"

class Dog:
def speak(self):
return "Bark"

def animal_sound(animal):
print(animal.speak())

# Using polymorphism
cat = Cat()
dog = Dog()
animal_sound(cat)  # Output: Meow
animal_sound(dog)  # Output: Bark

In this example, both Cat and Dog classes have a speak() method, but the implementation differs. The animal_sound() function can accept objects of both classes and call the appropriate speak() method, demonstrating polymorphism.

Polymorphism is a powerful concept in OOP that enhances flexibility and reusability, allowing different types of objects to be used interchangeably.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top