Polymorphism
Published Aug 2, 2021Updated Dec 14, 2022
Contribute to Docs
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())
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn General on Codecademy
- Start your programming journey with an introduction to the world of code and basic concepts.
- Includes 5 Courses
- With Certificate
- Beginner Friendly.4 hours
- Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!
- Includes 6 Courses
- With Professional Certification
- Beginner Friendly.75 hours