Python Abstract Class Implementing Interfaces and Polymorphism
In Python, an abstract class is a class that cannot be instantiated directly; it can only serve as a base for other classes. Abstract classes are typically used to define a set of interfaces or specifications that must be implemented by concrete subclasses.
Abstract classes in Python are usually implemented using the Abstract Base Class (ABC) mechanism. The abc module provides functionality to define and use abstract base classes, allowing you to specify abstract methods that enforce their implementation across derived classes. This enables the realization of interfaces and polymorphism.
Below is a simple example demonstrating how to define an abstract class using an abstract base class:
import abc
class Shape(metaclass=abc.ABCMeta): # Comment translated
@abc.abstractmethod
def area(self): # Comment translated
pass
class Rectangle(Shape): # Comment translated
def __init__(self, width, height): # Comment translated
self.width = width
self.height = height
def area(self): # Comment translated
return self.width * self.height
class Circle(Shape): # Comment translated
def __init__(self, radius): # Comment translated
self.radius = radius
def area(self): # Comment translated
return 3.14 * self.radius ** 2
r = Rectangle(5, 6)
print(r.area())
c = Circle(3)
print(c.area())
In this example, Shape is an abstract base class that defines an abstract method named area. Both Rectangle and Circle inherit from Shape and implement the area method accordingly. After instantiating objects of both classes, their respective areas can be calculated by calling the area method. Note that instances of Shape cannot be created directly.