继承与方法查找
Coddy 面向 C++ 开发者的 Python 课程 课程的第 39 课,共 48 课。
在本示例中,C++ 需要使用 virtual 才能通过基类引用实现运行时重写;override 则要求编译器检查匹配。Python 的普通方法直接在运行时对象上查找,无需 virtual 声明。super() 沿着方法解析顺序进行委托,在多重继承中并不一定指向某一个硬编码的父类。如果子类定义了 __init__,当需要基类初始化时,须显式调用 super().__init__。
C++17 摘录:main 函数内部
可运行的配套程序中已提供标准库头文件。
struct Base {
virtual std::string label() const { return "base"; }
virtual ~Base() = default;
};
struct Child : Base {
std::string label() const override { return Base::label() + "!"; }
};
Child child;
Base& base = child;
std::cout << base.label() << '\n';Python
class Base:
def label(self):
return "base"
class Child(Base):
def label(self):
return super().label() + "!"
print(Child().label())迁移陷阱
在 Python 中,将对象赋值给带有基类类型注解的变量名称不会切片(slice)该对象。而在 C++ 中,将 Child 复制到 Base 值类型的变量中可能会切掉派生类的状态和行为;在 C++ 中进行多态访问时,请使用引用或指针。
在可编辑的 Python 模块中完成以下任务。被锁定的 driver.py 用于运行和检查。请保留指定的导入和 API 名称。
挑战
入门实现 Pass(label, price),存储属性,并使其 cost() 方法返回整数价格。实现子类 DiscountPass(label, price, discount),通过 super().__init__ 初始化基类状态并存储 discount。重写 cost() 方法,使其返回基类费用减去折扣后的值,最低为 0。输入在单独的行中依次提供 label、非负价格和非负折扣。驱动程序会输出普通通行证和折扣通行证的 label 与费用,随后将折扣通行证的 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())
这节课包含一个小测验。开始学习即可作答,并记录你的进度。
面向 C++ 开发者的 Python 课程中的所有课
自己练习: Python 在线编译器