NextMethod 和 super
Coddy 面向 R 开发者的 Python 课程的第 39 课,共 48 课。
R S3 分派可以遵循类向量,而 NextMethod 会继续泛型分派到另一个适用的方法。Python 类会声明基类,并使用方法解析顺序。Python 的 super() 会创建一个代理,用于在当前类之后继续查找;你需要调用代理上的方法,并传入它所需的参数。这不是修改 R 类向量,也不能直接替代所有 NextMethod 用法。在单继承的构造函数中,super().__init__ 会先初始化继承部分,然后子类再添加自己的字段。重写的方法不会自动运行父类的实现,除非你显式委托调用。
R
label <- function(x) UseMethod("label")
label.child <- function(x) paste0(NextMethod(), "?")
label.base <- function(x) paste0(x$text, "!")
x <- structure(list(text="go"), class=c("child", "base"))
cat(label(x), "\n", sep="")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() 不会调用父类方法。你需要指定代理上的方法。
挑战
入门实现 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())
这节课包含一个小测验。开始学习即可作答,并记录你的进度。
面向 R 开发者的 Python中的所有课
自己练习: Python 在线编译器