您可以遍历子类实例的类。例如,假设我们定义了以下类和方法:
foo <- function(x, ...) {
UseMethod("foo")
}
bar <- function(x) {
class(x) <- c("bar", class(x))
return(x)
}
baz <- function(x) {
class(x) <- c("baz", "bar", class(x))
return(x)
}
foo.bar <- function(x, ...) {
cat("Bar:", x, "\n")
}
foo.default <- function(x, ...) {
cat("Default:", x, "\n")
}
我们已经创建了 的一个实例baz
,它的子类bar
:
my_instance <- baz(1)
现在我们可以找到所有可调用的方法,frombaz
和 parent(s):
unname(unlist(sapply(class(my_instance), function(x) methods(class = x))))
[1] "foo.bar" "all.equal.numeric"
[3] "as.data.frame.numeric" "as.Date.numeric"
[5] "as.POSIXct.numeric" "as.POSIXlt.numeric"
[7] "as.raster.numeric" "coerce,ANY,numeric-method"
[9] "Ops,nonStructure,vector-method" "Ops,structure,vector-method"
[11] "Ops,vector,nonStructure-method" "Ops,vector,structure-method"
现在,将它们全部称为更难,因为它们都有不同的论点。考虑以下:
sapply(unlist(sapply(class(my_instance), function(x) methods(class = x))),
function(f) get(f)(my_instance, 2))
Bar: 1
Error in as.Date.numeric(origin, ...) : 'origin' must be supplied
当然,我们可能还需要消除以下内容"Ops,nonStructure,vector-method"
:
z <- unname(unlist(sapply(class(my_instance), function(x) methods(class = x))))
z[!grepl(",", z)]
[1] "foo.bar" "all.equal.numeric" "as.data.frame.numeric"
[4] "as.Date.numeric" "as.POSIXct.numeric" "as.POSIXlt.numeric"
[7] "as.raster.numeric"