python polymorphism


python polymorphism

Polymorphism can be defined as declaring a uniform interface that is not aware of the type of the data, leaving implementation details to concrete data types that implement the interface. In general terms we can define it as different objects acts differently for same interface. In python we can implement polymorphism in two ways.

  1. polymorphism with functions
  2. polymorphism with classes

Python Polymorphism with Functions

  • In function based polymorphism we define a generic function and define the some functionality.
  • We use the same generic function to perform actions based on the parameters that sent.
  • Let's see an example for function based polymorphism in python.
    from collections import Iterable
    def find_length(a):
        if(isinstance(a, Iterable)):
           return len(a)
        else:
           return 1
    # try checking out
    print(find_length([1,2,3]))
    # output: 3
    print(find_length("123"))
    # output: 3
    print(find_length(123))
    # output: 1

 

Python Polymorphism with Classes

  • In class based polymorphism we define a method in all classes(i.e same method name in all classes).
  • we use the same method to perform the actions.
  • Let's see an example for function based polymorphism in python.
    class Animal(object):
        def __init__(self, name):
            self.name = name
    
        def talk(self):
            raise NotImplementedError
    
    
    class Dog(Animal):
        def talk(self):
            return "Bow...Bow..."
    
    
    class Cat(Animal):
        def talk(self):
            return "Meow...Meow..."
    
    
    class Human(Animal):
        def talk(self):
            return "I can talk more...."
    
    
    object_list = [Dog(name="Dog"), Cat("cat"), Human("Human")]
    
    for obj in object_list:
        print("Name: %s" % obj.name)
        print("Talk: %s" % obj.talk())
    # Output: 
    # Name: Dog
    # Talk: Bow...Bow...
    # Name: cat
    # Talk: Meow...Meow...
    # Name: Human
    # Talk: I can talk more....
    
    

We have seen simple examples above to understand the python polymorphism concept. Actually, We can do more with it.

Support Me on Patreon