Python教程37:抽象基类(ABC)
Python教程37:抽象基类(ABC) “约定优于配置。” 抽象基类(Abstract Base Class, ABC)是Python中定义接口规范的机制。今天我们学习如何使用abc模块创建抽象类,强制子类实现特定方法。 1. 什么是抽象基类 问题场景 没有抽象类时,接口规范靠文档和约定: 1class Shape: 2 """ 3 形状基类 4 - 子类应该实现area()和perimeter() 5 - 但没有强制机制 6 """ 7 def area(self): 8 raise NotImplementedError("子类必须实现area方法") 9 10 def perimeter(self): 11 raise NotImplementedError("子类必须实现perimeter方法") 12 13class Circle(Shape): 14 def __init__(self, radius): 15 self.radius = radius 16 17 def area(self): 18 import math 19 return math.pi * self.radius ** 2 20 21 # 忘记实现perimeter()了! 22 23# 问题:可以实例化不完整的类 24c = Circle(5) 25print(c.area()) # OK 26# print(c.perimeter()) # 运行时才报错! 抽象基类解决方案 1from abc import ABC, abstractmethod 2 3class Shape(ABC): 4 """ 5 抽象形状类 6 - 继承ABC 7 - 使用@abstractmethod标记抽象方法 8 - 不能直接实例化 9 - 强制子类实现所有抽象方法 10 """ 11 12 @abstractmethod 13 def area(self): 14 """计算面积(抽象方法)""" 15 pass 16 17 @abstractmethod 18 def perimeter(self): 19 """计算周长(抽象方法)""" 20 pass 21 22class Circle(Shape): 23 def __init__(self, radius): 24 self.radius = radius 25 26 def area(self): 27 import math 28 return math.pi * self.radius ** 2 29 30 # 如果不实现perimeter(),无法实例化 31 32# circle = Shape() # TypeError: 无法实例化抽象类 33 34class CompleteCircle(Shape): 35 def __init__(self, radius): 36 self.radius = radius 37 38 def area(self): 39 import math 40 return math.pi * self.radius ** 2 41 42 def perimeter(self): 43 import math 44 return 2 * math.pi * self.radius 45 46# 完整实现所有抽象方法才能实例化 47c = CompleteCircle(5) 48print(c.area()) # 78.54 49print(c.perimeter()) # 31.42 ABC的优势: ...