r - 你可以在 R6 对象中使用辅助函数吗?
问题描述
我试图避免在 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)
}
)
)
解决方案
你需要告诉你的班级在哪里可以找到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
推荐阅读
- java - 如何使不可更改的java类Serializable?
- c++ - 双引号传递给 QProcess::execute 的参数?
- php - Cakephp 错误:图像关联未在项目中定义
- python - python - 使用 Keras 和 TensorFlow 实现 LSTM 网络
- c++ - Tizen 的母语是什么?
- sapui5 - SAP WebIDE Uncaught ReferenceError: oView is not defined
- c# - 将索引值传递给 XAML 绑定表达式中的集合
- unit-testing - Jenkins共享库的单元测试
- python - Python Selenium:如何提取外层HTML
- python - 用于打印和手写数据的 Google Cloud OCR