我需要使用eval
引用类方法来调用。下面是一个玩具示例:
MyClass <- setRefClass("MyClass",
fields = c("my_field"),
methods = list(
initialize = function(){
my_field <<- 3
},
hello = function(){
"hello"
},
run = function(user_defined_text){
eval(parse(text = user_defined_text))
}
)
)
p <- MyClass$new()
p$run("hello()") # Error: could not find function "hello" - doesn't work
p$run(".self$hello()") # "hello" - it works
p$run("hello()") # "hello" - now it works?!
p <- MyClass$new()
p$run("my_field") # 3 - no need to add .self
我想我可以eval(parse(text = paste0(".self$", user_defined_text)))
,但我不太明白:
- 为什么
.self
需要评估方法,而不是字段? - 为什么
.self
用过一次就不需要了?