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 に答える