Как избежать предоплаты.self при использовании eval в ссылочном классе в R?

Мне нужно использовать 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 больше не нужен после того, как он был использован один раз?

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.

Я не уверен, что это очень полезно в вашем случае, когда пользователь, очевидно, может указать любой метод. Предлагая небольшой незапрашиваемый редакционный комментарий, я не уверен, "почему", вы бы хотели написать метод, который бы анализировал входной текст для методов; Я никогда не использовал эту парадигму сам.

Другие вопросы по тегам