Menu
CoddyTech

嵌入与继承

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

C 语言结构体嵌套存储了一个基类形状的成员,但其本身并不会创建语言层面的继承或虚分派。Python 在括号中声明子类,并沿着方法解析顺序查找方法。如果子类定义了 __init__,在需要该状态时必须显式调用基类初始化。super 指向该解析顺序中的下一个实现;在这个单继承示例中就是 Pass。重写的 cost 可以扩展基类行为,而无需重复查找当前价格。

C:完整的 example.c

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdarg.h>
struct Pass { int price; };
struct Discount { struct Pass base; int discount; };
int main(void) {
    struct Discount d = {{10}, 3};
    printf("%d\n", d.base.price - d.discount);
    return 0;
}

Python:完整的 example.py

class Pass:
    def __init__(self, price):
        self.price = price
    def cost(self):
        return self.price
class Discount(Pass):
    def __init__(self, price, discount):
        super().__init__(price)
        self.discount = discount
    def cost(self):
        return super().cost() - self.discount
print(Discount(10, 3).cost())

注意其中的区别

不要将 super 视为 C 指针强制类型转换或基类对象的独立副本。基类和子类的方法都在同一个实例上操作。对于可替换的协作对象应保持组合;只有在子类关系符合设计意图时才使用继承。

你的代码写在 pass_model.py、discount_pass.py 中。锁定的 driver.py 是入口文件,负责执行和检查,无法被编辑。

challenge icon

挑战

入门

实现 Pass(label,price),保存属性并从 cost() 返回当前价格。将 DiscountPass(label,price,discount) 实现为子类,通过 super().__init__ 初始化基类,并在重写的方法中返回 max(0, 基类成本减去折扣)。输入为 label 以及非负的 price/discount。驱动代码会打印普通卡和折扣卡的 label/cost 对,将折扣价格增加 10,然后打印其新成本;它还会检查子类继承关系。

在可编辑模块中实现指定的定义,不要包含输入或打印操作。驱动代码负责处理输入/输出,并可能在新的数据上再次调用 API,且不会产生额外输出。

C 语言的结构体嵌套并不提供 Python 继承功能。在此处请使用 super 显式初始化基类状态。

你的代码应编写在 pass_model.py 和 discount_pass.py 中。被锁定的 driver.py 是入口文件,负责运行和检查,无法进行编辑。

亲手试试

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自我测试

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

面向 C 开发者的 Python 课程中的所有课

自己练习: Python 在线编译器