首页 > 解决方案 > 你可以在 R6 对象中使用辅助函数吗?

问题描述

我试图避免在 R6 对象内重复。每次更新输入之一时,都必须更新计算/派生值。

下面的Cube对象演示了该问题。如果我更新任何width,heightdepth,则volume必须更新。

在这种情况下,公式是微不足道的,但在现实世界的情况下,情况并非总是如此。是否可以存储volCalc某个地方的知识,并允许在更新时set_width使用该功能进行更新?volume

现在,我可以使用下面的对象代码创建对象:

R> cc <- Cube$new(width = 5, height = 6, depth = 7)

但它在更新时中断

R> cc$set_width(10)
Error in volCalc(self$width, self$height, self$depth) : 
  could not find function "volCalc"

如您所见,我将如何计算立方体(volCalc)的体积的知识放在了两个地方;但可惜cc$set_width和朋友找不到它...

Cube <- R6Class("Cube",
  public = list(
    width = NULL,
    height = NULL,
    depth = NULL,
    volume = NULL,

    initialize = function(width, height, depth) {
      self$width <- width
      self$height <- height
      self$depth <- depth

      volCalc = function(W, H, D) W * H * D

      self$volume <- volCalc(width, height, depth)
    },

    volCalc = function(W, H, D) {
      self$volume <- W * H * D
      invisible(self)
    },    

    set_width = function(nWidth) {
      self$width <- nWidth
      volCalc(self$width, self$height, self$depth)
      invisible(self)
    },

    set_height = function(nHeight) {
      self$height <- nHeight
      volCalc(self$height, self$height, self$depth)
      invisible(self)
    },

    set_depth = function(nDepth) {
      self$depth <- nDepth
      volCalc(self$depth, self$depth, self$depth)
      invisible(self)
    }
  )
)

标签: rr6

解决方案


你需要告诉你的班级在哪里可以找到volCalc。它会在self. 因此,您需要做的就是将内部调用volCalc设为self$volCalc. 然后你可以这样做:

cc <- Cube$new(width = 5, height = 6, depth = 7)
cc
#> <Cube>
#>   Public:
#>     clone: function (deep = FALSE) 
#>     depth: 7
#>     height: 6
#>     initialize: function (width, height, depth) 
#>     set_depth: function (nDepth) 
#>     set_height: function (nHeight) 
#>     set_width: function (nWidth) 
#>     volCalc: function (W, H, D) 
#>     volume: 210
#>     width: 5

cc$set_width(10)
cc
#> <Cube>
#>   Public:
#>     clone: function (deep = FALSE) 
#>     depth: 7
#>     height: 6
#>     initialize: function (width, height, depth) 
#>     set_depth: function (nDepth) 
#>     set_height: function (nHeight) 
#>     set_width: function (nWidth) 
#>     volCalc: function (W, H, D) 
#>     volume: 420
#>     width: 10

推荐阅读