我喜欢set
R6 中的函数,因为它允许我更动态地构建对象。我希望能够从 中的空白设置对象开始R6Class()$private$settings
,然后在我有新对象和测试时动态添加到它。
set
覆盖对象,我想在调用R6Class(..)$new
. 这是可能的,还是我应该以不同的方式处理这个问题?我收到错误消息Error in element %in% names(self$private) : object 'self' not found
,所以我假设它与环境有关?
library(R6)
# build R6 template
templateSettings <- R6::R6Class(classname = "Template",
lock_objects = FALSE)
# updating an object in the R6Class, specifically a settings list in $private
newSetting <- function(element = NULL, name, value){
stopifnot(element %in% names(self$private))
stopifnot(!name %in% names(self$private[[element]]))
object <- list(value)
names(object) <- name
self$private[[element]] <- c(self$private[[element]], object)
invisible()
}
# create a settings list to try and update
templateSettings$set("private", "settings", list())
# try to assign in to templateSetting, assigns, but environment doesn't match
# templateSettings$set
assign("newSetting", newSetting, envir = environment(templateSettings$set))
templateSettings$newSetting
# dynamically update a settings object private$settings to be
# list(a=1, b=2). "Error in element %in% names(self$private) : object 'self' not found"
templateSettings$newSetting("settings", "a", 1)
templateSettings$newSetting("settings", "b", 2)
干杯,乔尼