【发布时间】:2011-11-03 16:16:03
【问题描述】:
我的问题:
为什么callNextMethod() 没有按预期将参数传递给下一个方法?
情况:
假设我有两个分层类 foo 和 bar(bar 是 foo 的子类),我有一个方法 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