这是在R中的访问器函数中使用callNextMethod()的扩展.
更新2017-03-25:为了说明这在加载方法时如何失败,而不是在构建的包中,我创建了一个虚拟包:https://github.com/zkamvar/inheritest#readme
我有一个继承另一个类foo的类栏,它们都有[method]的附加参数.foo的方法一致,但是第一次使用后bar的方法失败了.
Error in callNextMethod(x, i, j, ..., drop): bad object found as method (class "function")
4: stop(gettextf("bad object found as method (class %s)", dQuote(class(method))),
domain = NA)
3: callNextMethod(x, i, j, ..., drop) at #9
2: .local(x, i, j, ..., drop = drop)
1: BAR["x"]
Run Code Online (Sandbox Code Playgroud)
我有一个包实现了一个依赖于另一个包中的类的类.构建包时,一切正常,但是当我的包被简单地加载(使用devtools::load_all(".")
)时,我得到下面的行为.
foo <- setClass("foo", representation(x = "numeric", y = "numeric"))
bar <- setClass("bar", representation(distance = "numeric"), contains = "foo")
setMethod(f = "[", signature = signature(x = "foo", i = "ANY", j = "ANY", drop = "ANY"),
definition = function(x, i, j, ..., foo = TRUE, drop = FALSE) {
if (foo)
message("FOOOOOOO")
if (i == "x") {
return(x@x)
} else {
if (i == "y") {
return(x@y)
}
}
})
#> [1] "["
setMethod(f = "[", signature = signature(x = "bar", i = "ANY", j = "ANY", drop = "ANY"),
definition = function(x, i, j, ..., bar = TRUE, drop = FALSE) {
if (bar)
message("BAAAAAAR")
if (i == "distance") {
return(x@distance)
} else {
callNextMethod(x, i, j, ..., drop)
}
})
#> [1] "["
FOO <- new("foo", x = 1, y = 4)
BAR <- new("bar", x = 1, y = 4, distance = 3)
FOO["x"]
#> FOOOOOOO
#> [1] 1
BAR["x"]
#> BAAAAAAR
#> FOOOOOOO
#> [1] 1
FOO["x"]
#> FOOOOOOO
#> [1] 1
BAR["distance"]
#> BAAAAAAR
#> [1] 3
BAR["x"] # fails
#> BAAAAAAR
#> Error in callNextMethod(x, i, j, ..., drop): bad object found as method (class "function")
BAR["x", foo = FALSE]
#> BAAAAAAR
#> [1] 1
Run Code Online (Sandbox Code Playgroud)
注意:当我通过reprex传递它时,对BAR的第一次和最后一次调用也导致了错误,但我正在展示我在交互式会话中的体验.我使用的是R版本3.3.3
归档时间: |
|
查看次数: |
317 次 |
最近记录: |