获取继承自 S3 Class 及其 Parent 的方法

Get Methods Inherited from S3 Class and its Parent

如果我有一个继承自 parent 的 S3 class,我如何 return 我可以调用的通用方法列表 - 都来自 S3 class parent.

所以创建的objects的class是: c("my_s3_class", "parent_s3_class")

以下方法适用于 returnmy_s3_class 上的方法:

methods(class = my_s3_class)

但它不包括可调用的通用函数,而仅在 parent、parent_s3_class.

中实现

最终我想使用类似下面的方法调用每个方法(这有效,但不包括 parent 通用方法)。 get() 的使用意味着我不能使用 NextMethod(),否则这将是一个合理的解决方法。请注意,我有一个 my_s3_class 的实例,我将其表示为 my_s3_class_instance - 这只是一个实现细节。

result <- sapply(methods(class = class(my_s3_class_instance)[1]),
                 function(f) {
                     print(paste("Executing:",f))
                     get(f)(my_s3_class_instance)})

有什么想法吗?谢谢!

您可以迭代子类实例的 类。例如,假设我们定义了以下 类 和方法:

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)

现在我们可以找到所有可调用的方法,来自 baz 和 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"