Python 的 抽象基类

等级 5478 次按键

这演示了使用ABC和@abstractmethod的抽象基类来强制接口实现。

Python 代码

# 导入ABC和abstractmethod装饰器
1from abc import ABC, abstractmethod
2
# Shape继承ABC,只要还有抽象方法就不能实例化
3class Shape(ABC):
# @abstractmethod 装饰器将方法标记为必需
4 @abstractmethod
# area()返回float,这里只定义签名
5 def area(self) -> float:
# pass是占位语句,由子类负责实现
6 pass
7
# 周长的另一个抽象方法
8 @abstractmethod
# 子类必须实现perimeter方法
9 def perimeter(self) -> float:
# 抽象方法没有实现
10 pass
11
# Rectangle是Shape的具体子类
12class Rectangle(Shape):
# __init__ 初始化宽度和高度
13 def __init__(self, width: float, height: float):
# 将宽度存储为实例属性
14 self.width = width
# 将高度存储为实例属性
15 self.height = height
16
# area方法的具体实现
17 def area(self) -> float:
# 返回宽度乘以高度
18 return self.width * self.height
19
# 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

Python 等级 5 的更多代码示例

← 返回 Python 打字练习