[Python] abstract class

4.7 Abstract classes

In Python, an abstract class is a class that cannot be instantiated directly. Its main purpose is to define an interface so that other subclasses can inherit and implement the methods in it.
Specifically, abstract classes usually contain some abstract methods (abstract methods), these methods have only method names but no specific implementation, and need to be inherited by subclasses and implemented concretely. At the same time, if a class contains at least one abstract method, then this class must be declared as an abstract class.
Here is an example of an abstract class and a subclass implementation:

from abc import ABC, abstractmethod

class Shape(ABC):
    @abstractmethod
    def area(self):
        pass

class Rectangle(Shape):
    def __init__(self, width, height):
        self.width = width
        self.height = height
    
    def area(self):
        return self.width * self.height

rect = Rectangle(5, 10)
print(rect.area())
shape = Shape()  # 会报错,不能直接实例化抽象类

In the above example, we defined an abstract class Shape, which contains an abstract method area(), which has no specific implementation. Then we define a subclass Rectangle, which inherits Shape and implements the area() method.
When we create an instance of Rectangle and call the area() method, since Rectangle has already implemented the area() method, the program will not report an error and output the result normally.

Guess you like

Origin blog.csdn.net/crleep/article/details/131758715