S3 继承顺序
Coddy 面向 GDScript 开发者的 R 课程的第 39 课,共 48 课。
GDScript 中的 extends 和 super 提供了类继承,并能显式委托给父类行为。R 的 S3 分派则依照有序的类名向量进行,而 NextMethod 会继续沿着这条链调用。测试一下,增强方法是否只将下一个结果组合一次,而不是替换它或意外地重复它。
GDScript
extends SceneTree
class Base:
var price = 5
func total(quantity):
return price * quantity
class Delivery extends Base:
var fee = 2
func total(quantity):
return super.total(quantity) + fee
func _init():
var delivery = Delivery.new()
print(str(delivery.total(3)) + ":" + str(delivery.total(0)))
quit()R
sound <- function(x)UseMethod("sound")
sound.soft <- function(x)paste0(NextMethod(),"?")
sound.bell <- function(x)"ring"
x<-structure(list(),class=c("soft","bell"))
cat(sound(x),"\n",sep="")S3 类的顺序会影响分派链。
挑战
简单定义泛型函数 fee(x)。它的 parcel 方法返回 x$units*2。它的 urgent 方法返回 NextMethod()+5。当输入标志为 1 时,适配器会创建类 c("urgent","parcel"),否则创建类 parcel。输入内容是非负的 units,后面跟着标志 0 或 1。
保留已声明的公共 API。可见的锁定驱动程序会直接检查它,并打印 solve(lines)。输入符合所述约定;所有算术运算的结果都很小且有限。
你的代码应写在 Parcel.R 和 Exercise.R 中。main.R 会按顺序加载依赖,并包含提供的输入/输出代码;不能编辑它。
亲手试试
source("Parcel.R")
source("Exercise.R")
stopifnot(identical(fee(structure(list(units=7),class=c("urgent","parcel"))),19),identical(fee(structure(list(units=7),class="parcel")),14))
lines <- suppressWarnings(readLines(file("stdin"), warn=FALSE))
cat(solve(lines), "\n", sep="")
这节课包含一个小测验。开始学习即可作答,并记录你的进度。
面向 GDScript 开发者的 R中的所有课
自己练习: R 在线编译器