小编Max*_*nce的帖子

在R中的访问器函数中使用callNextMethod()

这与以下帖子在R中传递带有callNextMethod()的参数有关

我正在编写两个S4类的访问器,'foo'和'bar'.'bar'继承自foo,仅延伸几个插槽.我没有为类'bar'的对象编写完整的访问函数,而是在访问'foo'继承的插槽时将参数传递给callNextMethod().我的代码看起来像这样:

foo <- setClass("foo", representation(x = "numeric", y = "numeric"))
bar <- setClass("bar", representation(distance = "numeric"), contains = "foo")

setMethod("[", "bar", function(x, i, j, drop) {
  if (i == "distance") {
    return(x@distance)
    } else {
      callNextMethod()
    }
}
)

setMethod("[", "foo", function(x, i, j, drop) {
  if (i == "x") {
    return(x@x)
    } else {
      if (i == "y") {
        return(x@y)
      }
    }
}
)
Run Code Online (Sandbox Code Playgroud)

现在让我们试试这个:

f <- new("foo", x = 1, y = 2)
b <- new("bar", …
Run Code Online (Sandbox Code Playgroud)

inheritance r argument-passing s4

6
推荐指数
1
解决办法
153
查看次数

标签 统计

argument-passing ×1

inheritance ×1

r ×1

s4 ×1