在 Python 中创建抽象类
    
    
            Najwa Riyaz
    2023年1月30日
    
    Python
    Python Class
    
- 
          
            Python 3.4+ - 通过继承 ABC模块在 Python 中创建一个抽象类
- 
          
            Python 3.0+ - 通过继承 ABCMeta模块在 Python 中创建一个抽象类
- Python 中验证类是否抽象的方法
 
抽象类是受限类,因为它不能被实例化——你不能用它来创建对象。它只能从另一个类继承。
抽象类旨在定义多个子类可以继承的公共功能/行为,而无需实现整个抽象类。
在 Python 中,我们可以根据 Python 版本以不同方式创建基于抽象类。
Python 3.4+ - 通过继承 ABC 模块在 Python 中创建一个抽象类
在 Python 3.4 中,创建一个抽象类。
- 导入 ABC(抽象基类)模块。
from abc import ABC, abstractmethod
- 使用@abstractmethod装饰器声明抽象方法。
from abc import ABC, abstractmethod
class ExampleAbstractClass(ABC):
    @abstractmethod
    def abstractmethod(self):
        pass
下面是一个示例,其中 Vehicle 抽象类有两个子类,即 Car 和 Bike。Car 和 Bike 类有其独特的实现。
from abc import ABC, abstractmethod
class Vehicle(ABC):
    @abstractmethod
    def numberofwheels(self):
        pass
class Car(Vehicle):
    def numberofwheels(self):
        print("A Car has 4 wheels")
class Bike(Vehicle):
    def numberofwheels(self):
        print("A Bike has 2 wheels")
C = Car()
C.numberofwheels()
B = Bike()
B.numberofwheels()
输出:
A Car has 4 wheels
A Bike has 2 wheels
Python 3.0+ - 通过继承 ABCMeta 模块在 Python 中创建一个抽象类
在 Python 3.0+ 中,创建一个抽象类。
- 导入 ABCMeta(抽象基类)模块。
from abc import ABCMeta, abstractmethod
- 使用@abstractmethod装饰器声明抽象方法并提及metaclass=ABCMeta。
from abc import ABCMeta, abstractmethod
class Example2AbstractClass(metaclass=ABCMeta):
    @abstractmethod
    def abstractmethod2(self):
        pass
下面是一个例子。
from abc import ABCMeta, abstractmethod
class Vehicle(metaclass=ABCMeta):
    @abstractmethod
    def numberofwheels(self):
        pass
class Car(Vehicle):
    def numberofwheels(self):
        print("A Car has 4 wheels")
class Bike(Vehicle):
    def numberofwheels(self):
        print("A Bike has 2 wheels")
C = Car()
C.numberofwheels()
B = Bike()
B.numberofwheels()
输出:
A Car has 4 wheels
A Bike has 2 wheels
Python 中验证类是否抽象的方法
要验证创建的类是否确实是抽象类,我们应该实例化该类。抽象类将不允许实例化并抛出错误。
例如,如果我们实例化一个抽象如下。
x = ExampleAbstractClass()
然后,显示错误。
Can't instantiate abstract class ExampleAbstractClass with abstract methods abstractmethod
        Enjoying our tutorials? Subscribe to DelftStack on YouTube to support us in creating more high-quality video guides. Subscribe