Python – Advanced OOP
As we read earlier about the Inheritance in python , Now we will study about Python Polymorphism . In the advanced concept of OOP , Polymorphism is the second principle of Python Object -Oriented Programming. so lets start.
What is Polymorphism in Python ?
Polymorphism is a technique by which we can write two or more functions with the same name in a single class or in derived class is known as Polymorphism in Python.
Polymorphism functions in Python
We can support polymorphism using two tech :
- Function Overloading
- Function Overriding
Polymorphism Function Overloading is a technique by which we can write two or more functions with same name but different signature in a single class or a derived class is called as Function Overloading and It is also known as Compile – time Polymorphism.
Function Overloading Syntax :
def sum(a, b): statement def sum(a, b, c): statement
Function Overloading Example :
class C1: def sum(self, a, b): return a + b def sum(self, a, b, c): return a + b + c obj = C1() u, v = 2, 5 result = obj.sum(u, v) print(result)
Function Overloading Output :
result = obj.sum(u, v) TypeError: sum() missing 1 required positional argument: 'c'
Python do not support Function Overloading or Compile – time activity because python support only run – time activity.
Polymorphsim Function overriding is a technique by which we can write two or more function with same name and same signature in Derived class only is called as function overriding.
Function Overriding is used to achieve Run – time Polymorphism.
Run – Time Polymorphism :
Run – time Polymorphism is a technique by which we can change binding of function with object at run – time.
Function Overriding Syntax :
class Class1: def func(self): statement class Class2(Class1): def func(self): statement
Function Overriding Example :
class C1: def showData(self): print("I am in Class 1 ") class C2(C1): def showData(self): print("I am in Class 2") obj = C2() obj.showData()
Function Overriding Output :
«Previous Next» >
I am in Class 2