Polymorphism

Polymorphism

Polymorphism is the condition of occurrence in different forms.

Opertators

For integer data types, + operator is used to perform arithmetic addition operation.
For string data types, + operator is used to perform concatenation.

Thus + operator shows polymorphism in python.

Functions

print(len("Python"))
print(len(["Python", "Java", "C"]))
print(len({"Name": "Bhavya", "Age": "29"}))

Output:
6
3
2

Class polymorphism

Polymorphism allows different classes to have methods with the same name.

Classes

class Cat:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def info(self):
        print(f"I am a cat. My name is {self.name}. I am {self.age} years old.")

    def make_sound(self):
        print("Meow")


class Dog:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def info(self):
        print(f"I am a dog. My name is {self.name}. I am {self.age} years old.")

    def make_sound(self):
        print("Bark")


cat1 = Cat("Kitty", 2.5)
dog1 = Dog("Fluffy", 4)

for animal in (cat1, dog1):
    animal.make_sound()
    animal.info()
    animal.make_sound()

Output:
Meow
I am a cat. My name is Kitty. I am 2.5 years old.
Meow
Bark
I am a dog. My name is Fluffy. I am 4 years old.
Bark

In the above example, we have two classes Cat and Dog. They have similar structure and same method names info() and make_sound().

Though we are not linking these classes anywhere, we can pack the two different objects from two different classes as a tuple and iterate through it using a common animal variable. This is poosible due to the concept of polymorphism.

Polymorphism and Inheritance

In python, we can inherit the properties and methods from a parent child with the concept of inheritance. We can redefine certain methods and attributes specifically to fit the child class, which is known as Method Overriding.

Polymorphism allows us to access these overridden methods and attributes that have the same name as the parent class.

Method Overriding

from math import pi

class Shape:
    def __init__(self, name):
        self.name = name

    def area(self):
        pass

    def fact(self):
        return "I am a two-dimensional shape."

class Square(Shape):
    def __init__(self, length):
        super().__init__("Square")
        self.length = length

    def area(self):
        return self.length**2

    def fact(self):
        return "Squares have each angle equal to 90 degrees."

class Circle(Shape):
    def __init__(self, radius):
        super().__init__("Circle")
        self.radius = radius

    def area(self):
        return pi*self.radius**2

a = Square(4)
b = Circle(7)
print(b.fact())
print(a.fact())
print(b.area())

Output:
I am a two-dimensional shape.
Squares have each angle equal to 90 degrees.
153.93804002589985