Write a python program to illustrate the working of abstract method
The use of abstract base classes and inheritance in Python. Here's a breakdown of the code:
- from abc import ABC, abstractmethod: This line imports the ABC (Abstract Base Class) class and the abstractmethod decorator from the abc module. The ABC class is used to create abstract base classes, and the abstractmethod decorator is used to declare abstract methods within those classes.
- class Shape(ABC): This defines an abstract base class Shape that inherits from ABC. It has an abstract method area.
- @abstractmethod: This decorator is used to declare the area method as an abstract method. Abstract methods must be implemented by any concrete subclass of the Shape class.
- class Circle(Shape): This defines a subclass Circle of the Shape class. It implements the area method to calculate the area of a circle based on the radius.
- class Rectangle(Shape): This defines another subclass Rectangle of the Shape class. It implements the area method to calculate the area of a rectangle based on its length and width.
- Instances of the Circle and Rectangle classes are created by prompting the user to enter the required dimensions.
- The area method is called on the Circle and Rectangle objects to calculate and print the areas of the circle and rectangle, respectively.
Here's what the code does:
- It defines an abstract base class Shape with an abstract area method.
- It creates two concrete subclasses, Circle and Rectangle, which inherit from Shape and implement the area method.
- It prompts the user to enter the dimensions of a circle and a rectangle.
- It calculates and prints the areas of the circle and rectangle using the respective area methods.
Source Code
from abc import ABC, abstractmethod
class Shape(ABC):#Abstract base class
@abstractmethod
def area(self):
pass
class Circle(Shape):# Create a subclass of Shape
def __init__(self):
self.radius = float(input("Enter the Radius :"))
def area(self):
return 3.1415 * self.radius * self.radius
class Rectangle(Shape):# Create a subclass of Shape
def __init__(self):
self.length = float(input("Enter the Length :"))
self.width = float(input("Enter the Width :"))
def area(self):
return self.length * self.width
# Create instances of the subclasses
cir = Circle()
rect = Rectangle()
# Call the area method on the objects
print("Area of Circle :", cir.area())
print("Area of Rectangle :", rect.area())
Output
Enter the Radius :12
Enter the Length :24
Enter the Width :48
Area of Circle : 452.376
Area of Rectangle : 1152.0