R6 中自方法调用和私有方法调用的区别

Difference between self and private method call in R6

最近我发现自己在 R6 中编写了一些东西,并且在处理一些对象时很有趣,但出现了一个有趣的问题。当创建一个私有方法(例如 foo, of the bar)并在其他 public 方法中调用它时,如果我使用以下方式调用它,它就会工作:

self$foo

private$foo

我想问的是:这两种调用R6方法的方式有什么区别? 提前致谢!

来自 "Introduction to R6 classes" 小插图(强调我的):

self

Inside methods of the class, self refers to the object. Public members of the object (all you’ve seen so far) are accessed with self$x

private

Whereas public members are accessed with self, like self$add(), private members are accessed with private, like private$queue.

因此,即使您可以 通过self 访问私有方法,您也应该通过private 访问私有方法。不要依赖可能会消失的行为,请参阅文档如何说明它不应该那样工作。

就是说,我无法使用 self:

访问私有方法
library(R6)

bar <- R6Class("bar",
  private = list(
    foo = function() {
      message("just foo it")
    }
  ),
  public = list(
    call_self = function() {
      self$foo()
    },
    call_private = function() {
      private$foo()
    }
  )
)

b <- bar$new()
b$call_private()
# just foo it
b$call_self()
# Error in b$call_self() : attempt to apply non-function