Menu
CoddyTech

extends 与方法解析

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

Dart 使用 extends 声明基类,使用 super 调用继承的行为。Python 在括号中列出基类,并使用 super() 作为代理,按照方法解析顺序继续查找。对该代理调用指定的方法,并传入必需的参数。对于只有一个基类的初始化函数,super().__init__ 会先建立继承的状态,再添加子类的状态。Python 支持多重继承,因此不应将这个代理理解为在所有类层次结构中都硬编码引用直接父类。除非显式委托给继承的方法,否则重写的方法会取代对继承方法的常规查找。

Dart

class Base {
  String label(String text) => '$text!';
}
class Child extends Base {
  @override
  String label(String text) => '${super.label(text)}?';
}
void main() { print(Child().label('go')); }

Python

class Base:
    def label(self, text):
        return text + '!'
class Child(Base):
    def label(self, text):
        return super().label(text) + '?'
print(Child().label('go'))

移植陷阱

单独的 Python super() 表达式不会调用构造函数或方法。请在它后面调用目标方法。

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

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

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

自己练习: Python 在线编译器