【问题标题】:How to avoid prepending .self when using eval in a reference class in R?在 R 的引用类中使用 eval 时如何避免在前面添加 .self?
【发布时间】: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 &lt;- MyClass$new(); ls(environment(p$run)); p$hello; ls(environment(p$run)) 看到这一点
  • @MatthewPlourde 我发现这不是一个错误,它旨在进行惰性评估以提高性能。对于遇到此问题的其他人的一些有用资源:R-devel,stackoverflow question

标签: r reference-class


【解决方案1】:

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

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

【讨论】:

  • 在eval 之前添加usingMethods("hello") 可以解决此问题。谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-06-07
  • 1970-01-01
  • 2016-04-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多