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 more on Codecademy
- Skill path
Code Foundations
Start your programming journey with an introduction to the world of code and basic concepts.Includes 5 CoursesWith CertificateBeginner Friendly4 hours - Career path
Computer Science
Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!Includes 6 CoursesWith Professional CertificationBeginner Friendly75 hours - Career path
Front-End Engineer
Front-end engineers work closely with designers to make websites beautiful, functional, and fast.Includes 34 CoursesWith Professional CertificationBeginner Friendly115 hours