Polymorphism In Python-
-
- – In one liner it means “One name multiple task.”
-
-
Qsn-
How many types of polymorphism are there in Python?
-
Ans-
Only Run time polymorphism. It is also known as “Method overriding”.
-
-
-
Qsn-
Why we are not having compile time polymorphism in python.
-
Ans-
Because we have dynamic memory allocation concept in python. And we have args and argv by which we can take as many as value we can in method argument. In Other programming language. Overloading can be achieved by changing the data type of passing argument or by changing the no of passing argument. but in python this is automatically achieved by other concept thats why explicit concept of method overloading or compile time polymorphism is not exist here. but if still we try to overload a function then the orverloaded function will replace the first function in python which will break our implementation so better not to try this concept in python as it doesn’t support here.
-
-
Method Overriding-
- – Defining a same method name and same signature in child class as we have in parent class.
- – Super() method can be used to access the parent class functionality.
Ex-
class Test1: def display(self): print("In Test1") class Test2(Test1): def display(self): print("In Test2") class Test3(Test2): def display(self): print("In Test3") def show(self): print("In show") Test1.display(self) Test2.display(self) Test3.display(self) self.display() print("By Super method") Test3.display(self) #super.display(self) super(Test3, self).display() super(Test2, self).display() def main(): obj = Test3() print("From main method") obj.display() Test1.display(obj) Test2.display(obj) Test3.display(obj) obj.show() Test3.main() Output- From main method In Test3 In Test1 In Test2 In Test3 In show In Test1 In Test2 In Test3 In Test3 By Super method In Test3 In Test2 In Test1