ABC
module (Abstract Base Classes).from abc import ABC
class ClassName(ABC):
# Abstract class definition
pass
from abc import ABC
class Shape(ABC): # Abstract class
def calculate_area(self): # Abstract method
pass
In this example, Shape
is an abstract class, and calculate_area
is an abstract method. The implementation of calculate_area
will be defined in the derived classes.from abc import ABC
class Shape(ABC):
def calculate_area(self):
pass
class Rectangle(Shape):
length = 5
breadth = 3
def calculate_area(self):
return self.length * self.breadth
class Circle(Shape):
radius = 4
def calculate_area(self):
return 3.14 * self.radius * self.radius
# Create objects for derived classes
rec = Rectangle()
cir = Circle()
print("Area of a rectangle:", rec.calculate_area())
print("Area of a circle:", cir.calculate_area())
Area of a rectangle: 15
Area of a circle: 50.24
If the derived classes do not implement the abstract method, Python will throw an error.from abc import ABC
class Shape(ABC):
def print_message(self):
print("This is a method in the abstract class Shape.")
def calculate_area(self):
pass
class Rectangle(Shape):
length = 5
breadth = 3
def calculate_area(self):
return self.length * self.breadth
# Create an object of the derived class
rec = Rectangle()
rec.print_message()
print("Area of a rectangle:", rec.calculate_area())
This is a method in the abstract class Shape.
Area of a rectangle: 15