Polymorphism in Python

Polymorphism is one of the main pillars of OOPs.Polymorphism means having multiple or many forms.It means Same Function name performing Different Actions

Ways of Achieving Polymorphism 

We can Achieve Polymorphism in Python by for ways:-
  • Duck Typing
  • Operator Overloading 
  • Method Overloading
  • Method Overriding

Duck Typing

Duck Typing is a Type System of the Dynamically Typed Programming Languages.Programming Languages Like Python,Ruby,Perl and Ruby are some of the popular examples of Dynamically Typed Language.

Using Duck Typing, we do not check types at all. Instead, we check for the presence of a given method or attribute.There is a popular phrase on Duck Typing.

            “If it looks like a duck and quacks like a duck, it’s  a duck”
class String:
def __len__(self):
return 2893
# Driver's code
if __name__ == "__main__":
str1 = String()

Method Overloading

Method Overloading is a powerful technique in which we can use functions with different actions by having different type of data or different numbers of parameters with same function name.Below is a simple example of Method Overloading.

class Person:
def SayHello(self, name=None):
if name is not None:
print('Hello ' + name)
print('Hello ')
# Create instance
obj = Person()
# Call the method
# Call the method with a parameter

Method Overriding

Method Overriding is the technique in which the Function's body is changed in the child class after being inherited from the parent class.
class A:
def __init__(self,name):
self.name = name
def Hello(self):
print("Hello " + self.name)
class B(A):
def __init__(self,name):
self.name = name
def Hello(self):
print("Hi " + self.name)
obj1 = A("Skv")
obj2 = B("Skv2")
Multiple Inheritance
When a class is derived from more than one base class it is called Multiple Inheritance.

class A:
def say(self):
print("Inside A")
class B:
def tell(self):
print("Inside B")
class C(A,B):
def say(self):
print("Inside C") obj = C()

Multilevel Inheritance

Multilevel Inheritance: When we have a child and grandchild relationship.
class Parent():
def show(self):
print("I am inside Parent")
class Child(Parent):
def display(self):
print("I am inside Child")
class GrandChild(Child):
def show(self):
print("I am inside Grand Parent")
# Driver code
 g = GrandChild()
Operator Overloading
Operator Overloading: When we use same operator for performing different Actions,then it's called Operator Overloading.
#operator overloading
print("Hello " + "Skv")

Thanks for Reading

1 comment :

Copyright © DevTipsNTricks. Designed by OddThemes