InterviewSolution
| 1. |
Does Python support polymorphism? Explain with a suitable example. |
|
Answer» Polymorphism is an important feature of object oriented programming. It comes into play when there are commonly named methods across subclasses of an abstract base class. Polymorphism is the ability to present the same interface for differing underlying forms. This allows functions to use objects of any of these polymorphic classes without needing to be AWARE of distinctions across the classes. If class B inherits from class A, it doesn’t have to inherit everything about class A, it can do some of the things that class A does differently. It is most commonly used while dealing with inheritance. Method in Python class is implicitly polymorphic. Unlike C++ it need not be MADE explicitly polymorphic. In the following example, we first define an abstract class CALLED shape. It has an abstract method area() which has no implementation. import abc class Shape(metaclass=abc.ABCMeta): def __init__(self,tp): self.shtype=tp @abc.abstractmethod def area(self): passTwo subclasses of shape - Rectangle and Circle are then CREATED. They provide their respective implementation of inherited area() method. class Rectangle(Shape): def __init__(self,nm): super().__init__(nm) self.l=10 self.b=20 def area(self): return self.l*self.b class Circle(Shape): def __init__(self,nm): super().__init__(nm) self.r=5 def area(self): import math return math.pi*pow(self.r,2)Finally we set up objects with each of these classes and put in a collection. r=Rectangle('RECT') c=Circle('circle') shapes=[r,c] for sh in shapes: print (sh.shtype,sh.area())Run a for loop over a collection. A generic call to area() method calculates the area of respective shape. Output: rect 200 circle 78.53981633974483 |
|