R引用类 - 如何确定您是否在继承方法中?

mch*_*hen 5 oop inheritance r reference-class

对于给定的引用类方法,如何确定它是否被继承?更一般地说,如何确定我的继承树有多远?

例如,如果我的设置是:

A <- setRefClass("A",
        methods = list(foo = function() whosMethod())
    )
B <- setRefClass("B",
        contains = "A",
        methods = list(bar = function() whosMethod())
    )
b <- B()
Run Code Online (Sandbox Code Playgroud)

理想情况下,我想whosMethod()给我一些类似的东西

> b$foo()
[1] "A"         # or maybe a numeric value like: [1] 1L

> b$bar()
[1] "B"         # or maybe a numeric value like: [1] 0L
Run Code Online (Sandbox Code Playgroud)

请注意class(.self),这"B"与上面的例子总是会有所不同.

动机 - 自定义事件

我希望除了方法之外的其他东西也有类似继承的行为,例如自定义事件.我的方法可能raise(someEvent)并且在实例化期间我传递事件处理程序来处理那些事件,例如

MyDatabase <- setRefClass(....)
datasourceA <- MyDatabase(....,
    eventHandlers = list(
        someEvent = function() message("Hello from myObj!"),
        beforeInsert = function(data) {
            if (!dataIsValid(data))
                stop("Data is not valid!")
        }
    )
)
Run Code Online (Sandbox Code Playgroud)

现在,如果子类定义了一个已经由父类定义的事件处理程序,那么我需要知道应该覆盖哪个事件处理程序.特别是,如果一个methodA()登记handlerA()的someEvent和methodB()在子类中注册handlerB()了同一个事件,尝试注册时,handlerA()在methodA()我需要知道的是,我在一个父类的方法,这样,如果handlerB()已经注册,我不重写.

能够从子类调用父事件处理程序(如callSuper()方法可用)也是很好的.

Rap*_*ter 0

尝试这个:

遍历继承图并获取各自的方法

methodsPerClass <- function(x) {
    if (!inherits(x, "envRefClass")) {
        stop("This only works for Reference Class objects")
    }
    ## Get all superclasses of class of 'x' //
    supercl <- selectSuperClasses(getClass(class(b)), directOnly=FALSE)
    ## Get all methods per superclass //
    out <- lapply(c(class(x), supercl), function(ii) {
        ## Get generator object //
        generator <- NULL
        if (inherits(getClass(ii), "refClassRepresentation")) {
            generator <- getRefClass(ii)
        }
        ## Look up method names in class defs //
        out <- NULL
        if (!is.null(generator)) {
            out <- names(Filter(function(x) {
                    attr(x, "refClassName") == generator$className
                }, 
                as.list(generator$def@refMethods))
            )        
        }
        return(out)
    })
    names(out) <- supercl
    ## Filter out the non-reference-classes //
    idx <- which(sapply(out, is.null))
    if (length(idx)) {
        out <- out[-idx]
    }
    ## Nicer name for actual class of 'x' //
    idx <- which(names(out) == "envRefClass") 
    if (length(idx)) {
        names(out)[idx] <- class(x)
    }
    return(out)
}
Run Code Online (Sandbox Code Playgroud)

我确信人们可以想出一些更好的方法来过滤掉非引用类,以便摆脱最后的“idx”部分,但它是有效的。

这会给你:

methodsPerClass(x=b)
$A
[1] "bar"

$B
[1] "foo"

$.environment
 [1] "import"       "usingMethods" "show"         "getClass"     "untrace"     
 [6] "export"       "callSuper"    "copy"         "initFields"   "getRefClass" 
[11] "trace"        "field"     
Run Code Online (Sandbox Code Playgroud)

查询哪些方法具体属于哪个类

whosMethod <- function(x, method) {
    mthds <- methodsPerClass(x=x)
    out <- lapply(method, function(m) {
        pattern <- paste0("^", m, "$")
        idx <- which(sapply(mthds, function(ii) {
            any(grepl(pattern, ii))
        }))
        if (!length(idx)) {
            stop(paste0("Invalid method '", m, 
                "' (not a method of class '", class(x), "')"))
        }
        out <- names(idx)
    })
    names(out) <- method
    return(out)
}
Run Code Online (Sandbox Code Playgroud)

这会给你:

whosMethod(x=b, method="foo")
$foo
[1] "B"

whosMethod(x=b, method=c("foo", "bar"))
$foo
[1] "B"

$bar
[1] "A"

whosMethod(x=b, method=c("foo", "bar", "nonexisting"))
Error in FUN(c("foo", "bar", "nonexisting")[[3L]], ...) : 
  Invalid method 'nonexisting' (not a method of class 'B')
Run Code Online (Sandbox Code Playgroud)

对“B”类的所有方法运行它:

whosMethod(x=b, method=unlist(methodsPerClass(x=b)))
$bar
[1] "A"

$foo
[1] "B"

$import
[1] ".environment"

$usingMethods
[1] ".environment"

$show
[1] ".environment"

$getClass
[1] ".environment"

$untrace
[1] ".environment"

$export
[1] ".environment"

$callSuper
[1] ".environment"

$copy
[1] ".environment"

$initFields
[1] ".environment"

$getRefClass
[1] ".environment"

$trace
[1] ".environment"

$field
[1] ".environment"
Run Code Online (Sandbox Code Playgroud)