gpt4 book ai didi

r - 为什么方法继承会杀死额外的参数?

转载 作者:行者123 更新时间:2023-12-04 01:06:47 25 4
gpt4 key购买 nike

我想在我的泛型中设置一些标志(在调用 UseMethod() 之前,我知道很多:)),然后在方法中使用和/或更新这些标志。

像这样:

g <- function(x) {
y <- 10
UseMethod("g")
}
g.default <- function(x) {
c(x = x, y = y)
}
g.a <- function(x) {
y <- 5 # update y from generic here
NextMethod()
}

这在直接跳转到默认方法时有效:
g(structure(.Data = 1, class = "c"))  # here y is never updated
# x y
# 1 10

但是当我通过 NextMethod() , y神秘消失:
g(structure(.Data = 1, class = "a"))  # here y is updated, but cannot be found
# Error in g.default(structure(.Data = 1, class = "a")) :
# object 'y' not found

我已经想出了如何解决这个问题,只需绕过 y很多:
f <- function(x, ...) {
y <- 10
UseMethod("f")
}
f.default <- function(x, ..., y = 3) {
c(x = x, y = y)
}
f.a <- function(x, ...) {
y <- 5
NextMethod(y = y)
}

这产生
f(structure(.Data = 1, class = "c"))
# x y
# 1 3
f(structure(.Data = 1, class = "a"))
# x y
# 1 5

我的问题是: 为什么NextMethod()在上面g().* -example 杀死额外的 y参数 ?

我想到了 UseMethod()的全部意义和 NextMethod()是在调用之间传递任何和所有对象,而无需手动传递它们:

NextMethod works by creating a special call frame for the next method. If no new arguments are supplied, the arguments will be the same in number, order and name as those to the current method but their values will be promises to evaluate their name in the current method and environment.



我特别困惑 UseMethod()似乎传递了 y ,但是 NextMethod()没有。

最佳答案

正如@Roland 所指出的,这种行为被记录在案:

来自 help("UseMethod") 关于UseMethod()的段落注释(强调):

UseMethod creates a new function call with arguments matched as they came in to the generic. Any local variables defined before the call to UseMethod are retained (unlike S). Any statements after the call to UseMethod will not be evaluated as UseMethod does not return.



各款约 NextMethod() (已在上面引用)仅说明:

NextMethod works by creating a special call frame for the next method. If no new arguments are supplied, the arguments will be the same in number, order and name as those to the current method but their values will be promises to evaluate their name in the current method and environment. Any named arguments matched to … are handled specially: they either replace existing arguments of the same name or are appended to the argument list. They are passed on as the promise that was supplied as an argument to the current environment. (S does this differently!) If they have been evaluated in the current (or a previous environment) they remain evaluated. (This is a complex area, and subject to change: see the draft ‘R Language Definition’.)



总之就是 UseMethod()做了一些特别和非凡的事情:它传递局部变量。 NextMethod() ,像往常一样,不这样做。
UseMethod()是异常(exception),不是 NextMethod() .

关于r - 为什么方法继承会杀死额外的参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48782552/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com