【问题标题】:Order of methods in R reference class and multiple filesR参考类和多个文件中的方法顺序
【发布时间】:2014-08-13 07:10:57
【问题描述】:

我真的不喜欢 R 引用类的一件事:编写方法的顺序很重要。假设你的课程是这样的:

myclass = setRefClass("myclass",
                       fields = list(
                           x = "numeric",
                           y = "numeric"
                       ))


myclass$methods(
    afunc = function(i) {
        message("In afunc, I just call bfunc...")
        bfunc(i)
    }
)

myclass$methods(
    bfunc = function(i) {
        message("In bfunc, I just call cfunc...")
        cfunc(i)
    }
)


myclass$methods(
    cfunc = function(i) {
        message("In cfunc, I print out the sum of i, x and y...")
        message(paste("i + x + y = ", i+x+y))
    }
)



myclass$methods(
    initialize = function(x, y) {
        x <<- x
        y <<- y
    }
)

然后你启动一个实例,并调用一个方法:

x = myclass(5, 6)
x$afunc(1)

你会得到一个错误:

Error in x$afunc(1) : could not find function "bfunc"

我对两件事感兴趣:

  • 有没有办法解决这个麻烦?
  • 这是否意味着我永远无法将一个非常长的类文件拆分为多个文件? (例如,每种方法一个文件。)

【问题讨论】:

    标签: r oop reference-class


    【解决方案1】:

    调用bfunc(i) 不会调用该方法,因为它不知道它正在操作的对象是什么!

    在您的方法定义中,.self 是被方法化的对象 (?)。所以把你的代码改成:

    myclass$methods(
        afunc = function(i) {
            message("In afunc, I just call bfunc...")
            .self$bfunc(i)
        }
    )
    

    bfunc 也是如此)。您是来自 C++ 还是某种语言,其中方法中的函数会在对象的上下文中自动调用?

    某些语言会更明确地说明这一点,例如在 Python 中,像您这样的具有一个参数的方法在定义时实际上有两个参数,并且会是:

      def afunc(self, i):
      [code]
    

    但称为:

      x.afunc(1)
    

    然后在afunc 中有一个引用xself 变量(虽然称它为self 是一个通用约定,它可以被称为任何东西)。

    在 R 中,.self 是洒在引用类上的一点魔法。即使您愿意,我认为您也无法将其更改为 .this

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-10-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-07-15
      相关资源
      最近更新 更多