Header Ads Widget

Ticker

6/random

Python Polymorphism

Python Polymorphism

In Python, polymorphism allows objects of different types to be treated as objects of a common base type. This is typically achieved through the use of a common interface or a shared method. 

Here's an explanation with examples:


1. Polymorphic Function:


```python

class Cat:

    def make_sound(self):

        return "Meow!"


class Dog:

    def make_sound(self):

        return "Woof!"


def animal_sound(animal):

    return animal.make_sound()


# Using the polymorphic function with objects of different classes

my_cat = Cat()

my_dog = Dog()


print(animal_sound(my_cat)) # Outputs: Meow!

print(animal_sound(my_dog)) # Outputs: Woof!

```


Here, both the `Cat` and `Dog` classes have a `make_sound` method. The `animal_sound` function takes an object of any class with a `make_sound` method, demonstrating polymorphism.


2. Duck Typing:


```python

class Duck:

    def quack(self):

        return "Quack!"


class RobotDuck:

    def quack(self):

        return "Beep beep quack!"


# Using duck typing for polymorphism

def make_duck_quack(duck):

    return duck.quack()


# Both Duck and RobotDuck can quack

my_duck = Duck()

my_robot_duck = RobotDuck()


print(make_duck_quack(my_duck)) # Outputs: Quack!

print(make_duck_quack(my_robot_duck)) # Outputs: Beep beep quack!

```


In duck typing, the suitability of an object is determined by its behavior (presence of specific methods) rather than its type.


3. Polymorphism with Inheritance:


```python

class Shape:

    def area(self):

        pass


class Circle(Shape):

    def __init__(self, radius):

        self.radius = radius


    def area(self):

        return 3.14 * self.radius**2


class Square(Shape):

    def __init__(self, side_length):

        self.side_length = side_length


    def area(self):

        return self.side_length**2


# Using polymorphism with a common base class

circle = Circle(radius=5)

square = Square(side_length=4)


print(f"Circle Area: {circle.area()}") # Outputs: 78.5

print(f"Square Area: {square.area()}") # Outputs: 16

```


Here, both `Circle` and `Square` inherit from a common base class `Shape`. They provide their own implementations of the `area` method, demonstrating polymorphism.


Polymorphism enhances code flexibility and reusability by allowing code to work with objects of different types as long as they support a common interface or behavior.

Post a Comment

0 Comments