在R中的引用类中使用eval时,如何避免预加.self?

在R中的引用类中使用eval时,如何避免预加.self?,r,reference-class,R,Reference Class,我需要使用eval调用引用类方法。下面是一个玩具示例: MyClass <- setRefClass("MyClass", fields = c("my_field"), methods = list( initialize = function(){ my_field <<- 3 }, hello = function(){ "hello"

我需要使用
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

MyClass“为什么”问题总是很难回答;通常答案是“因为”。在
?setRefClass
上,我们最终

Only methods actually used will be included in the environment
corresponding to an individual object.  To declare that a method
requires a particular other method, the first method should
include a call to '$usingMethods()' with the name of the other
method as an argument. Declaring the methods this way is essential
if the other method is used indirectly (e.g., via 'sapply()' or
'do.call()'). If it is called directly, code analysis will find
it. Declaring the method is harmless in any case, however, and may
aid readability of the source code.

我不确定这对您的情况是否完全有用,因为用户显然能够指定任何方法。提供一些未经请求的编辑评论,我不确定您是否希望编写一个将输入文本解析为方法的方法;我自己从来没有使用过这种模式。

这似乎是一个bug,或者至少是不受欢迎的行为。请注意,在调用
p$run(“hello()”
之前,只需使用
p$hello
p
检索
hello
,后者也可以执行w/o error
p$hello
更改
p$run
的环境。你可以通过
p@MatthewPlourde看到这一点。我发现这不是一个bug,它是用来懒散地评估以提高性能的。一些对其他遇到此问题的人有用的资源:,stackoverflow在
eval
之前使用方法(“hello”)
添加
。谢谢