Polymorphism

  • Polymorphism = ability of object of different types to be handled by a common interface. This means a method of a class can do different things in subclasses. Python has duck typing polymorphism or sub type polymorphism.
  • Polymorphism = Because derived objects share the same interface as their parents, the calling code can call any function in that class’ interface. At run-time, the appropriate function will be called depending on the type of object passed leading to possibly different behaviors.
  1. Ad-hoc polymorphism (Overloading) is also known as function overloading, we use typing in order to resolve which function will be invoked. We may have two functions, both called fn, where one accepts an int parameter, while the other accepts a String parameter, and the right function to invoke is chosen based on the type of parameter being passed.
  2. Parametric Polymorphism - generics and type inference (C++) using Template
  3. Sub-type polymorphism (via. inheritance) - In python mostly used. In polymorphism we see subclass (Cat and Dog) inheriting from the parent class (Animal) and overriding the method Talk.
  4. Duck typing - In case of duck typing we don’t create a subclass instead new class is created with method having same name but different function. Duck typing with modules.
    1. Duck Typing = where the type or the class of an object is less important than the methods it defines. When you use duck typing, you do not check types at all. Instead, you check for the presence of a given method or attribute
  • In polymorphism we see subclass (Cat and Dog) inheriting from the parent class (Animal) and overriding the method Talk.
  • In case of duck typing we don’t create a subclass instead new class is created with method having same name but different function.

References

SuperMade with Super