开放类与 super
Coddy 面向 Kotlin 开发者的 Python 课程的第 39 课,共 48 课。
Kotlin 中的类和方法默认是 final,要重写它们,需要使用 open 或接口契约。Python 中的普通类和方法无需使用 open 或 override 关键字即可重写。Python 的 super 会按照方法解析顺序继续查找方法。如果 Python 子类定义了 __init__,并且需要继承的初始化状态,就必须调用继承的初始化方法。
Kotlin
open class BaseLabel { open fun text() = "base" }
class LoudLabel : BaseLabel() { override fun text() = super.text() + "!" }
fun main() { println(LoudLabel().text()) }Python
class BaseLabel:
def text(self):
return "base"
class LoudLabel(BaseLabel):
def text(self):
return super().text() + "!"
print(LoudLabel().text())移植陷阱
不要在 Python 中添加 Kotlin 的 override 语法。如果拼错了 Python 方法名,它会悄悄定义一个不同的方法,除非测试或工具发现了这个问题。
在可编辑模块中完成任务。锁定的 driver.py 负责执行;请保留必需的 API 名称。
挑战
入门实现 Pass(label, price),保存属性,并让 cost() 返回整数价格。实现子类 DiscountPass(label, price, discount),通过 super().__init__ 初始化基类状态,并保存 discount。重写 cost(),使其返回基准费用减去折扣后的结果,且最低为 0。输入内容依次为标签、非负价格和非负折扣,每项单独占一行。驱动程序会输出普通通行证和折扣通行证的标签及费用,然后将折扣通行证的 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())
这节课包含一个小测验。开始学习即可作答,并记录你的进度。
面向 Kotlin 开发者的 Python中的所有课
自己练习: Python 在线编译器