Advertisement

Polymorphism in python

Polymorphism in Python


In Python, polymorphism refers to the ability of an object to take on multiple forms. This can be achieved in a number of ways, including inheritance, duck typing, and method overloading.


Polymorphism in Python


Inheritance is a way of creating a new class that is a modified version of an existing class. The new class is called the subclass, and the existing class is the superclass. The subclass inherits all the attributes and behaviors of the superclass, and can also have additional attributes and behaviors of its own.

For example, consider the following class hierarchy:

class Animal:

    def __init__(self, name, species):
        self.name = name
        self.species = species
    def make_sound(self):
        print("Some generic animal sound")

class Cat(Animal):
    def __init__(self, name, breed, toy):
        super().__init__(name, species="Cat")
        self.breed = breed
        self.toy = toy

    def make_sound(self):
         print("Meow"
class Dog(Animal):
    def __init__(self, name, breed):
        super().__init__(name, species="Dog")
        self.breed = breed

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


In this example, the Animal class is the superclass, and the Cat and Dog classes are subclasses. The subclasses inherit the name and species attributes and the make_sound method from the superclass, but they also have additional attributes and behaviors of their own.

Polymorphism can be demonstrated using the isinstance function and the issubclass function:

cat = Cat("Fluffy", "Siamese", "Ball")
dog = Dog("Buddy", "Labrador")

print(isinstance(cat, Animal)) # True
print(isinstance(dog, Animal)) # True
print(isinstance(cat, Cat)) # True
print(isinstance(dog, Dog)) # True
print(issubclass(Cat, Animal)) # True
print(issubclass(Dog, Animal)) # True
print(issubclass(Cat, Dog)) # False


The isinstance function returns True if an object is an instance of a specified class, and False otherwise. In this case, both the cat and dog objects are instances of the Animal class, as well as their respective subclasses.

The issubclass function returns True if a class is a subclass of a specified class, and False otherwise. In this case, both the Cat and Dog classes are subclasses of the Animal class, but the Cat class is not a subclass of the Dog class.

Polymorphism can also be achieved through duck typing, which is a way of determining whether an object can be used in a particular way, without requiring the object to be a member of a specific class.

For example, consider the following function:

def play_with_animal(animal):
     animal.make_sound()
     animal.play()


This function expects an animal object that has both a make_sound method and a play method. It does not matter what.


Post a Comment

0 Comments