【发布时间】:2020-02-17 13:40:12
【问题描述】:
我试图避免在 R6 对象内重复。每次更新输入之一时,都必须更新计算/派生值。
下面的Cube 对象演示了这个问题。如果我更新width、height 或depth 中的任何一个,则必须更新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)
}
)
)
【问题讨论】: