Menu
CoddyTech

超越特征的继承

Coddy 面向 Rust 开发者的 Python 课程的第 39 课,共 48 课。

Rust 有 trait 和组合,但没有类继承,无法像子类那样复用父类中存储的字段。Python 支持子类化和方法重写。super() 会遵循方法解析顺序,并委托给下一个适用的实现;它不是对象副本。在简单的单继承示例中,它会调用基类方法。持有基类值的 Rust 包装器可以通过显式委托提供类似的输出,但这属于组合,而不是继承。

main 中的 Rust 代码片段

struct Base;
impl Base { fn label(&self) -> String { String::from("base") } }
struct Child { base: Base }
impl Child { fn label(&self) -> String { self.base.label() + "!" } }
println!("{}", Child { base: Base }.label());

Python

class Base:
    def label(self):
        return "base"
class Child(Base):
    def label(self):
        return super().label() + "!"
print(Child().label())

移植陷阱

Rust trait 默认方法和 Python 的 super 调用并不是相同的机制。在多重继承中,super 遵循计算得出的顺序,而不只是调用硬编码的父类。

在可编辑的 Python 文件中实现指定的 API。锁定的 driver.py 会运行程序并提供输入和输出。请保持其中的导入和名称不变。

challenge icon

挑战

入门

实现 Pass(label, price),保存属性,并让 cost() 返回整数价格。实现子类 DiscountPass(label, price, discount),通过 super().__init__ 初始化基类状态,并保存 discount。重写 cost(),使其返回基础费用减去折扣后的结果,最低为零。输入依次为标签、非负价格和非负折扣,每项各占一行。驱动程序会打印普通通行证和折扣通行证的标签与费用,然后将折扣通行证的 price 增加 10,并打印新的费用。请根据当前状态计算。

锁定的驱动程序负责处理输入和输出。只提交必需的类和函数定义,并使用准确的 API 名称。不要在你的类中读取输入或打印内容。

锁定的驱动程序还会在运行时验证所需的子类关系。

你的代码应写入可编辑文件 pass_model.py 和 discount_pass.py。driver.py 包含提供的输入/输出代码和 API 检查,无法编辑。保留提供的导入语句;不要在可编辑模块中读取输入或打印内容。

亲手试试

from pass_model import Pass
from discount_pass import DiscountPass

assert issubclass(DiscountPass, Pass), "Required subclass relationship missing"
label = input()
price, discount = int(input()), int(input())
a, b = Pass(label, price), DiscountPass(label, price, discount)
print(a.label, a.cost())
print(b.label, b.cost())
b.price += 10
print(b.cost())
quiz icon自我测试

这节课包含一个小测验。开始学习即可作答,并记录你的进度。

面向 Rust 开发者的 Python中的所有课

自己练习: Python 在线编译器