Hadley指出,一个班级作业将class(x) <- c("A", "B")执行以下操作:
如下一节所述,R按照在类向量中出现的顺序查找方法。因此,在此示例中,就像类A从类B继承一样-如果未为A定义方法,则它将回落到B。但是,如果您切换类的顺序,则相反!
在这里,我的理解是:
print.mytest <- function(x, ...) {
cat(paste0("Just a test for class mytest: ", x, "\n")
}
x <- 1
print(class(x))
# [1] "numeric"
print(x)
# [1] 1
class(x) <- c("mytest")
print(class(x))
# [1] "mytest"
print(x)
# [1] "Just a test for class mytest: 1"
Run Code Online (Sandbox Code Playgroud)
这是我不了解的地方:我期望使用类,numeric但从未使用过。因此,[1] 1在第二种情况下,我期望输出为。
x <- 1
print(class(x))
# [1] "numeric"
class(x) <- c(class(x), "mytest")
print(class(x))
# [1] "numeric" "mytest"
print(x) # Not understood (http://adv-r.had.co.nz/S3.html)
# [1] "Just a test for class mytest: 1"
x <- 1
print(class(x))
# [1] "numeric"
class(x) <- c("mytest", class(x))
print(class(x))
# [1] "mytest" "numeric"
print(x) # Not understood...
# [1] "Just a test for class mytest: 1"
Run Code Online (Sandbox Code Playgroud)
该文档?class还指出
当将通用函数fun应用于具有类属性c(“ first”,“ second”)的对象时,系统将搜索一个名为fun.first的函数,如果找到该函数,则将其应用于该对象。如果找不到这样的函数,则尝试一个名为fun.second的函数。如果没有任何类名会产生合适的函数,则使用fun.default函数(如果存在)。
谢谢下面的答案
x <- 1
print(class(x))
class(x) <- c("mytest2", "mytest")
print(class(x))
print(x)
# Just a test for class mytest2: 1
x <- 1
print(class(x))
class(x) <- c("mytest", "mytest2")
print(class(x))
print(x)
# Just a test for class mytest: 1
Run Code Online (Sandbox Code Playgroud)
如果在类向量中找不到用于类的方法,则仅使用默认方法。在问题中没有,print.numeric但是有一个,print.mytest因此在两种情况下都使用它。它从不寻找a,print.default因为它可以在类向量中列出的方法中找到一个方法。
也就是说,它查看的第一个元素,class(x)如果在这种情况下print找到了该类的方法,它将使用它。如果不是,它将继续到的第二个元素class(x)并寻找print该类的方法。如果找到它,它将使用它。如果只class(x)找到和的两个元素,则找不到方法,则将使用默认方法。
在情况下class(x)是c("numeric", "mytest")没有print.numeric方法,因此寻找一个print.mytest和发现它所以使用它。
在情况下class(x)为c("mytest", "numeric")它找到print.mytest,所以它使用它。
因此,在两种情况下print.mytest都是选择的方法。