Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR PYTHON

python polymorphism

import math
class Shape:
    def __init__(self, name):
        self.name = name
    def area(self):
        pass
    def __str__(self):
        return self.name

class Square(Shape):
    def __init__(self, length):
        super().__init__("Square")
        self.length = length
    def area(self):
        return self.length**2

class Circle(Shape):
    def __init__(self, radius):
        super().__init__("Circle")
        self.radius = radius
    def area(self):
        return math.pi * self.radius**2 

a = Square(4)
b = Circle(7)
for shape in (a, b):
    print(f'Area of {shape} is {shape.area():.2f}')
# Area of Square is 16.00
# Area of Circle is 153.94
Source by www.geeksforgeeks.org #
 
PREVIOUS NEXT
Tagged: #python #polymorphism
ADD COMMENT
Topic
Name
2+9 =