【问题标题】:Problems passing arguments with callNextMethod() in R在 R 中使用 callNextMethod() 传递参数的问题
【发布时间】:2011-11-03 16:16:03
【问题描述】:

我的问题:

为什么callNextMethod() 没有按预期将参数传递给下一个方法?

情况:

假设我有两个分层类 foobarbarfoo 的子类),我有一个方法 foobar 可以为这两个类调度(即,两个类都有方法)。

此外,(子)类bar的方法在与callNextMethod()进行一些计算后调用foo的方法。

两个方法都有相同的附加参数(默认),应该传递给foo 的方法,只有它是相关的。

setClass("foo", representation(x = "numeric"))
setClass("bar", contains = "foo")

setGeneric("foobar", function(object, ...) standardGeneric("foobar"))

setMethod("foobar", "foo", function(object, another.argument = FALSE, ...) {
    print(paste("in foo-method:", another.argument))
    if (another.argument) object@x^3
    else object@x^2
})

setMethod("foobar", "bar", function(object, another.argument = FALSE, ...) {
    print(paste("in bar-method:", another.argument))
     object@x <- sqrt(object@x)
    callNextMethod()
})

问题描述:
参数未按预期传递,但默认值取自方法定义。具体来说,在第一个方法中,参数与调用中指定的一样 (TRUE),但是在下一个方法中它会更改为 FALSE

o1 <- new("bar", x = 4)

foobar(o1, another.argument = TRUE)

给予

[1] "in bar-method: TRUE"
[1] "in foo-method: FALSE"
[1] 4

我希望将another.argument 传递给下一个方法,以便在对foo 方法的调用中它也是TRUE


?callNextMethod 我知道它应该按预期工作(即,命名参数在调用中传递):

对于出现在原始调用中的形式参数,比如 x,有 是下一个方法调用中的对应参数,等效于 x = X。实际上,这意味着下一个方法看到相同的实际 参数,但参数只计算一次。


我的第二个问题:如何将 another.argument 传递给下一个方法。 (我真的很想在这两种方法中保留默认参数)

【问题讨论】:

  • 我很难过。如果您在这里没有得到任何答案,您可以在r-devel 邮件列表中尝试...

标签: oop r methods argument-passing s4


【解决方案1】:

我认为这与定义签名与泛型不同的方法的方式有关(在函数 .local 中)

> selectMethod(foobar, "bar")
Method Definition:

function (object, ...) 
{
    .local <- function (object, another.argument = FALSE, ...) 
    {
        print(paste("in bar-method:", another.argument))
        object@x <- sqrt(object@x)
        callNextMethod()
    }
    .local(object, ...)
}

Signatures:
        object
target  "bar" 

defined "bar" 

解决方法是定义泛型和方法以具有相同的签名

setGeneric("foobar",
    function(object, another.argument=FALSE, ...) standardGeneric("foobar"),
    signature="object")

或将参数显式传递给callNextMethod

setMethod("foobar", "bar", function(object, another.argument = FALSE, ...) {
    print(paste("in bar-method:", another.argument))
     object@x <- sqrt(object@x)
    callNextMethod(object, another.argument, ...)
})

【讨论】:

  • 您对 S4 问题的另一个很好的回答。非常感谢。
  • 谢谢。为什么我们不能将其称为错误而不是“不正当”或“轻率”……?因为试图弄清楚观察到的行为如何与文档中的内容相矛盾,这让我的大脑很痛苦? (S4 在最好的时候伤害了我的大脑。)
  • 我完全同意(但不同意 S4 伤害大脑的部分。我实际上喜欢 S4)。
  • 'bug' 暗示了一些无意的疏忽,我对作者的大脑没有这种洞察力。所以我已经完全取消了判断。我鼓励对 R-devel 进行报告,否则能够改变这一点的人对问题一无所知。
  • 我赞同 R-devel 报告的建议。恕我直言,这是一个错误,因为我想不出任何与代码行为一致的文档的合理解释。 (也就是说,可以通过更改文档来修复错误......)
猜你喜欢
  • 2014-09-12
  • 1970-01-01
  • 2020-11-08
  • 2021-09-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多