Polymorphism is one of the four principles of object-oriented programming (OOP). It promotes dynamic inheritance of child classes from their parent class in order to make use of these features themselves in code.
With polymorphism, child classes are able to inherit methods from their parent class for use. This ability to inherit functionality from parent classes not only speeds up the development process, but also helps us reason and understand our code more intuitively as we can see the correlation between objects for easier understanding and manipulation of source code.
from math import piclass Shape:def __init__(self, name):self.name = namedef area(self):passdef fact(self):return "I am a two-dimensional shape."def __str__(self):return self.nameclass Square(Shape):def __init__(self, length):super().__init__("Square")self.length = lengthdef area(self):return self.length**2def fact(self):return "Squares have each angle equal to 90 degrees."class Circle(Shape):def __init__(self, radius):super().__init__("Circle")self.radius = radiusdef area(self):return pi*self.radius**2a = Square(4)b = Circle(7)print(b)print(b.fact())print(a.fact())print(b.area())
- Anonymous contributorAnonymous contributor3077 total contributions
- christian.dinh2481 total contributions
- theeguru___45 total contributions
- Christine_Yang271 total contributions
- garanews222 total contributions