Python abc 模块
实例
定义一个抽象基类并实现它:
from abc import ABC, abstractmethod
class Shape(ABC):
@abstractmethod
def area(self):
pass
class Square(Shape):
def __init__(self, s):
self.s = s
def area(self):
return self.s * self.s
sq = Square(3)
print(isinstance(sq, Shape))
print(sq.area())
亲自试一试 »
定义和用法
abc 模块提供用于创建抽象基类 (ABC) 和抽象方法装饰器的工具。
使用 ABC 定义子类必须实现的通用接口。这有助于强制执行契约,并提高大型代码库的清晰度。
成员
| 成员 | 描述 |
|---|---|
| ABC | 定义抽象类的基类。 |
| ABCMeta | 用于定义抽象类的元类;提供注册和抽象方法检查。 |
| abstractclassmethod() | 已弃用。请改用 classmethod 装饰器和 abstractmethod。 |
| abstractmethod() | 用于将方法标记为抽象方法的装饰器(必须在子类中重写)。 |
| abstractproperty() | 已弃用。请改用 property 装饰器和 abstractmethod。 |
| abstractstaticmethod() | 已弃用。请改用 staticmethod 装饰器和 abstractmethod。 |
| get_cache_token() | 返回当前 ABC 缓存令牌(ABC 修改时会更改)。 |
| update_abstractmethods() | 重新计算类的抽象方法集。 |

