r - R 类的顺序会导致什么?

标签 r function class

Hadley指出类作业 class(x) <- c("A", "B")执行以下操作:

As discussed in the next section, R looks for methods in the order in which they appear in the class vector. So in this example, it would be like class A inherits from class B - if a method isn’t defined for A, it will fall back to B. However, if you switched the order of the classes, the opposite would be true!

这里,我的理解是:

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"

这是我不明白的地方:我期望使用类 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"

文档 ?class还说

When a generic function fun is applied to an object with class attribute c("first", "second"), the system searches for a function called fun.first and, if it finds it, applies it to the object. If no such function is found, a function called fun.second is tried. If no class name produces a suitable function, the function fun.default is used (if it exists).


感谢下面的回答

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 

最佳答案

如果没有找到类向量中的类的方法,它只会使用默认方法。在问题中没有 print.numeric 但有一个 print.mytest 所以它在两种情况下都使用。它从不寻找 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 都是所选择的方法。

关于r - R 类的顺序会导致什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58041941/

相关文章:

php - 在循环中或不在循环中实例化一个新类?

R - 隐藏的线条

r - 需要一种有效的方法来将因子值从数据框的一列更改为另一列

javascript - 如何捕获Javascript :void(0)

objective-c - 从 Objective-C 类访问对象的 Swift 函数

delphi - 如何访问子类中的函数?

r - 有条件地同时将值分配给两列 R

r - Shiny 的嵌套/多个对话框

php - 奇怪的 PHP 自动加载问题

src\class-name.cpp 中的 C++ 类错误