【发布时间】:2013-07-03 14:58:00
【问题描述】:
我需要使用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用过一次就不需要了?
【问题讨论】:
-
这似乎是一个错误,或者至少是不受欢迎的行为。请注意,在调用
p$run("hello()")之前,只需使用p$hello从p检索hello,也可以使后者执行无错误。p$hello改变了p$run的环境。您可以通过p <- MyClass$new(); ls(environment(p$run)); p$hello; ls(environment(p$run))看到这一点
标签: r reference-class