Python 的 抽象基类
等级 5478 次按键
这演示了使用ABC和@abstractmethod的抽象基类来强制接口实现。
Python 代码
# 导入ABC和abstractmethod装饰器1from abc import ABC, abstractmethod2 # Shape继承ABC,只要还有抽象方法就不能实例化3class Shape(ABC): # @abstractmethod 装饰器将方法标记为必需4 @abstractmethod # area()返回float,这里只定义签名5 def area(self) -> float: # pass是占位语句,由子类负责实现6 pass7 # 周长的另一个抽象方法8 @abstractmethod # 子类必须实现perimeter方法9 def perimeter(self) -> float: # 抽象方法没有实现10 pass11 # Rectangle是Shape的具体子类12class Rectangle(Shape): # __init__ 初始化宽度和高度13 def __init__(self, width: float, height: float): # 将宽度存储为实例属性14 self.width = width # 将高度存储为实例属性15 self.height = height16 # area方法的具体实现17 def area(self) -> float: # 返回宽度乘以高度18 return self.width * self.height19 # perimeter方法的具体实现20 def perimeter(self) -> float: # 返回2乘以(宽度+高度)21 return 2 * (self.width + self.height)22 # 创建宽度5、高度3的Rectangle实例23rect = Rectangle(5, 3)# 打印面积(5*3 = 15)和周长(2*(5+3) = 16)24print(f"Area: {rect.area()}, Perimeter: {rect.perimeter()}")运行结果
Area: 15, Perimeter: 16
可以用这段代码练习打字。成绩不会计入排行榜。
这段代码中的符号
这段 Python 代码中需要输入的符号及其出现次数。
(× 12)× 12:× 11.× 8,× 5_× 4-× 4>× 4=× 3"× 2