Implementing Abstract Methods
To implement the abstract methods defined in an abstract base class, you need to create a concrete subclass that inherits from the abstract class and provides the implementation for the abstract methods.
Here's an example:
from abc import ABC, abstractmethod
class Shape(ABC):
@abstractmethod
def area(self):
pass
@abstractmethod
def perimeter(self):
pass
class Rectangle(Shape):
def __init__(self, width, height):
self.width = width
self.height = height
def area(self):
return self.width * self.height
def perimeter(self):
return 2 * (self.width + self.height)
class Circle(Shape):
def __init__(self, radius):
self.radius = radius
def area(self):
return 3.14 * self.radius ** 2
def perimeter(self):
return 2 * 3.14 * self.radius
In this example, the Rectangle
and Circle
classes are concrete subclasses of the Shape
abstract class. They both provide the implementation for the area()
and perimeter()
abstract methods.
classDiagram
class Shape {
<
>
+area()
+perimeter()
}
class Rectangle {
-width: float
-height: float
+area()
+perimeter()
}
class Circle {
-radius: float
+area()
+perimeter()
}
Shape <|-- Rectangle
Shape <|-- CircleBy implementing the abstract methods, the Rectangle
and Circle
classes can be instantiated and used like any other concrete class. This allows you to write code that works with any subclass of the Shape
abstract class, as long as they implement the required methods.
rect = Rectangle(5, 10)
print(rect.area()) ## Output: 50.0
print(rect.perimeter()) ## Output: 30.0
circle = Circle(3)
print(circle.area()) ## Output: 28.26
print(circle.perimeter()) ## Output: 18.84
Implementing abstract methods is a key aspect of using abstract classes in Python. It ensures that your code follows a consistent interface and that all related classes provide the expected functionality.