3

我需要使用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用过一次就不需要了?
4

1 回答 1

3

“为什么”的问题总是难以回答;通常答案是“因为”。?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.

我不确定这对您的情况是否完全有帮助,用户显然可以指定任何方法。提供一些未经询问的编辑评论,我不确定“为什么”您要编写一个将输入文本解析为方法的方法;我自己从未使用过这种范式。

于 2013-07-03T15:54:37.730 回答