更新父字段时更新 R6 对象中的依赖字段

Update a dependent field in R6 object when a parent field is updated

我是 R6 和面向对象编程的新手,所以我不确定谈论对象内部字段之间依赖关系的正确方法。

我的对象具有依赖于对象内部其他字段的字段。我希望这些依赖字段在其中一个输入更新时自动更新。

我已经想出一个手动方法来执行此操作,但认为可能有更好的方法。我玩过 active 个字段,但我无法让它们工作。

这个例子应该说清楚了。我有一个对象 quad,它接受 widthheight 并计算 area。我希望 areawidthheight 更新时自动更新。

这似乎是 active fields 旨在实现的目标之一,但我无法使它们起作用。

出于阐述的目的,我通过在每个字段的 set 方法中包含 self$area 的重新计算行来实现我的目标。

这应该怎么做?

library(R6)
quad <- R6Class("quad", public =
                list(width = NULL,
                     height = NULL,
                     area = NULL,
                     initialize = function(width, height) {
                         self$width <- width
                         self$height <- height
                         self$area = self$width * self$height
                         self$greet()
                     },
                     set_width = function(W) {
                         self$width <- W
                         self$area = self$width * self$height #hack
                     }, 
                     set_height = function(H) {
                         self$height <- H
                         self$area = self$width * self$height #hack
                     }, 
                     greet = function() {
                         cat(paste0("your quad has area: ", self$area, ".\n"))
                     })
                )
#
> quad1 <- quad$new(5, 5)
your quad has area: 25.

> quad1$set_height(10)
> quad1$area
[1] 50    

主动绑定本质上是一个无需使用()即可调用的函数,因此它看起来像一个常规字段。

在下面的示例中,area 是一个活动绑定,并且会在您每次访问它时进行计算。

library(R6)
Quad <- R6Class(
  "Quad",
  public = list(
    initialize = function(width, height) {
      self$width <- width
      self$height <- height
    },
    width = NULL,
    height = NULL
  ),
  active = list(
    area = function() {
      self$width * self$height
    }
  )
)


q <- Quad$new(8, 3)
q$area
#> [1] 24

q$height <- 5
q$area
#> [1] 40