【发布时间】:2016-01-30 23:35:40
【问题描述】:
使用 R6 类时,在类之外定义调用其他方法的方法的正确方法是什么?
考虑以下示例,如果函数func 以交互方式使用,它可能会分派给另一个函数。但是,如果这样做,则其他功能无法访问私有环境。如果我以这种方式定义类,是否应该传递环境?
## General function defined outside R6 class
func <- function(x) {
if (missing(x) && interactive()) {
ifunc()
} else {
private$a <- x * x
}
}
## If interactive, redirect to this function
ifunc <- function() {
f <- switch(menu(c('*', '+')), '1'=`*`, '2'=`+`)
private$a <- f(private$a, private$a)
}
## R6 test object
Obj <- R6::R6Class("Obj",
public=list(
initialize=function(a) private$a <- a,
geta=function() private$a,
func=func # defined in another file
),
private=list(
a=NA
)
)
## Testing
tst <- Obj$new(5)
tst$func(3)
tst$geta() # so func sees 'private'
# [1] 9
tst$func() # doesn't see 'private'
ifunc() 中的错误(来自 #3):找不到对象“私有”
【问题讨论】: