Polymorphism in Python

 Polymorphism in Python


Polymorphism is a way to use objects of different classes in a similar way, allowing them to be interchangeable. Here's an example of using polymorphism to call a method on different objects:


python


class Circle:

    def __init__(self, radius):

        self.radius = radius

    

    def area(self):

        return 3.14 * self.radius ** 2


class Square:

    def __init__(self, side):

        self.side = side

    

    def area(self):

        return self.side ** 2


shapes = [Circle(5), Square(3)]


for shape in shapes:

    print("Area:", shape.area())

In this example, we define two classes, Circle and Square, that both have an area method that calculates the area of the shape. We create a list of shapes that includes one instance of each class, and then iterate over the list, calling the area method on each shape and printing the result.

No comments:

Post a Comment

The Importance of Cybersecurity in the Digital Age

 The Importance of Cybersecurity in the Digital Age Introduction: In today's digital age, where technology is deeply intertwined with ev...