正确执行S3方法:什么时候应该使用省略号? [英] Correct implementation of a S3-method: When should I use ellipsis?

查看:125
本文介绍了正确执行S3方法:什么时候应该使用省略号?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我意识到使用S3类结构的好处。
是否有推荐使用哪个变体的建议:

I realized the benefit of using S3 class structures. Is there any recommendation which variant to use:


  1. fun.class1<-function(x ,...)

  2. fun.class2<-函数(x)

  1. fun.class1 <- function(x, ...)
  2. fun.class2 <- function(x)

似乎,它们总是同时起作用...

It seems, they always work both...

可重现的示例:

fun.default <- function(x) {
  print("default")
  return(x)
}
fun.class1 <- function(x, ...) {
  print("class1 ellipsis")
  res <- x[y]
  return(res)
}
fun.class2 <- function(x) {
  print("class2 only x")
  res <- x[y]
  return(res)
}
my_fun <- function(x) {
  res <- UseMethod("fun")
  return(res)
}

x <- structure(c(1, 2), class = c("numeric", "class1"))
y <- 1
my_fun(x)
# [1] "class1 ellipsis"
# [1] 1
x <- structure(c(1, 2), class = c("numeric", "class2"))
y <- 1
my_fun(x)
# [1] "class1 ellipsis"
# [1] 1


推荐答案

简而言之:


使您的界面尽可能小。

Make your interfaces as small as possible.

翻译为您的省略号问题:仅在确实需要时使用省略号

Translated to your ellipsis question: Only use an ellipsis, when you really need it.

恕我直言,您只能在真正使用省略号时使用它。我可以想到到目前为止我已经看到的三种情况:

IMHO you should only introduce an ellipsis when you really use it. I can think of three cases I have seen so far:


  1. 您的某些S3类需要其他不需要的参数;

  2. 您的某些S3类(或全部)使用非标准评估来评估某些参数。因此,您可能需要一个可以容忍数量不断变化的参数的接口;

  3. @Roland的观点是可以容忍指定未使用参数的用户。

总之,我建议以下内容:

In short I'd suggest the following:

只要您正在编程的S3类主要用于您自己或由另一个函数调用:不要仅仅因为将来可能会使用它而引入任何省略号参数。仅介绍您真正使用的参数。在需要上述一种使用情况时,立即引入省略号。

As long as you are programming S3 classes that are mainly used by yourself or called by another function: Don't introduce any ellipsis argument just because you might use it someday in the future. Only introduce the arguments you really use. Introduce the ellipsis as soon as one of the use cases above is needed.

希望这会有所帮助。

还有另一个提示:看来,它们总是一样的。.。不,我不这么认为。在您的示例中,它们可以全部工作,因为它们在全局环境中找到 y 。另请参见此处。据我所知,您应该将这两个版本分别视为 my_fun(x,...) my_fun(x,y) ..

And another hint: It seems, they always work both... No, I don't think so. In your example they work all, because they find y in the global environment. See also here. As far as I can see you should think of the two versions as my_fun(x, ...) respectively my_fun(x, y)..

这篇关于正确执行S3方法:什么时候应该使用省略号?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆