gpt4 book ai didi

r - 在 R 的引用类中使用 eval 时如何避免在前面加上 .self?

转载 作者:行者123 更新时间:2023-12-02 00:07:22 25 4
gpt4 key购买 nike

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

最佳答案

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

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

关于r - 在 R 的引用类中使用 eval 时如何避免在前面加上 .self?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17451418/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com