Polymorphism in Python

05 min read

Polymorphism,  or dynamic binding, is the ability to use a class instance without regard for its type. It is handled entirely through the attribute lookup process described for inheritance in the previous articles. Whenever a method is accessed as obj.method(), method is located by searching within the instance itself, the instance's class definition, and then base classes, in that order. The first match found is used as the method. For special methods such as __getattr__(), Python first searches in the instance's class definition, followed by the base classes.

We shall now use an example to understand the use of polymorphism in Python,

Task: Create two classes:  Cat and Dog, and present them with their respective sounds.  Make instances to call the classes using the method.

class Dog(object):
         def sound(self):
                       print "Bow Bow!!!"
 
class Cat(object):
      def sound(self):
              print "meaw meaw "
 
def makeSound(animalType):
          animalType.sound()
 
 
D = Dog()
C = Cat()
 
makeSound(D)
makeSound(C)

Output:
Bow Bow!!! meaw meaw
POST A NEW COMMENT
     
  • Input (stdin)

    Output (stdout)


    Input (stdin)

    Your Output (stdout)

    Expected Output

    Compiler Message

    Input (stdin)

    2    3

    Your Output (stdout)

    5

    Expected Output

    5

    Compiler Message

    5

    Error