添加此问题后,我在GitHub 上提问,他们很快给出了答案。这是答案的重新发布:
get <- function(x = list()) {
class <- R6::R6Class(classname = "class")
lapply(names(x), function(name) {
fn <- eval(substitute(function() subst_name, list(subst_name = name)))
class$set("public", name, fn)
})
class
}
x <- get(x = list(a = 10, b = 20))$new()
x$a()
如果您在打印 x$a 时想要更好的名称,您可以使用以下命令清除名称引用:
attr(fn, "srcref") <- NULL
编辑:
这是添加到类的值是函数的示例(这是我改进的代码):
constructor <- function(public = list(), private = list()) {
class <- R6::R6Class(classname = "class")
lapply(names(public), function(name) {
if (is.function(public[[name]])) {
env <- environment(public[[name]])
env$self <- public
env$private <- private
fn <- eval(substitute(function(...) fn(...), list(fn = public[[name]])))
class$set("public", name, fn)
} else {
class$set("public", name, public[[name]])
}
})
class
}
test <- function() {
a <- 10
class <- constructor(
public = list(
a = function() { a + self$b },
b = 20
)
)
x <- class$new()
x$a()
}
test()
如果您想访问 super 您需要使用以下代码:
编辑2:
component <- function(public = NULL,
private = NULL,
static = NULL,
...) {
class <- R6::R6Class(...)
r6.class.add(class, public)
r6.class.add(class, private)
class$extend <- make.extend(class)
class
}
#' helper function for adding properties to R6Class
r6.class.add <- function(class, seq) {
prop.name <- as.character(substitute(seq)) # so we don't need to write name as string
lapply(names(seq), function(name) {
if (is.function(seq[[name]])) {
## the only way to have scope from when function was create with self and private
## eval substitute simply circument R6 encapsulation and use scope from where function
## was created (closure) and env.fn patch the env of inner function so it get self
## and private as magic names - this is done so component function the same as
## when R6Class is created inline - so component is referencial transparent and can
## be replaced with R6Class
fn <- eval(substitute(function(...) {
## patch function env
fn <- fn.expr # fn.expr will be inline function expression
parent <- parent.env(environment())
## we don't overwrite function scope so you can nest one constructor
## in another constructor
env <- new.env(parent = environment(fn))
env$self <- parent$self
env$super <- parent$super
env$private <- parent$private
environment(fn) <- env
fn(...)
}, list(fn.expr = seq[[name]], name = name)))
class$set(prop.name, name, fn)
} else {
class$set(prop.name, name, seq[[name]])
}
})
}
而不是env$self <- parent$self
你也可以使用get("self", parent)
(它会在环境链中搜索变量)。