R 中 'this' 或 'self' 的等价物

The equivalent of 'this' or 'self' in R

我正在寻找 R 中 python 的 'self' 关键字或 java 的 'this' 关键字的等价物。在下面的示例中,我正在制作一个S4 对象来自不同 S4 对象的方法,需要将指针传递给自己。语言中有什么可以帮助我做到这一点吗?

MyPrinter <- setRefClass("MyPrinter",
  fields = list(obj= "MyObject"),
  methods = list(
    prettyPrint = function() {
      print(obj$age)
      # do more stuff
    }
  )
)

MyObject <- setRefClass("MyObject",
  fields = list(name = "character", age = "numeric"),
  methods = list(
    getPrinter = function() {
      MyPrinter$new(obj=WHAT_GOES_HERE) #<--- THIS LINE
    }
  )
)

我可以用一个独立的方法来做这件事,但我希望在 R 中有一个很好的面向对象的方式来做这个操作。谢谢

参考 class (RC) 对象基本上是包装环境的 S4 对象。环境保存 RC 对象的字段,并设置为其方法的封闭环境;这就是对字段标识符的非限定引用如何绑定到实例的字段。我能够在环境中找到一个 .self 对象,我相信这正是您正在寻找的对象。

x <- MyObject$new(); ## make a new RC object from the generator
x; ## how the RC object prints itself
## Reference class object of class "MyObject"
## Field "name":
## character(0)
## Field "age":
## numeric(0)
is(x,'refClass'); ## it's an RC object
## [1] TRUE
isS4(x); ## it's also an S4 object; the RC OOP system is built on top of S4
## [1] TRUE
slotNames(x); ## only one S4 slot
## [1] ".xData"
x@.xData; ## it's an environment
## <environment: 0x602c0e3b0>
environment(x$getPrinter); ## the RC object environment is set as the closure of its methods
## <environment: 0x602c0e3b0>
ls(x@.xData,all.names=T); ## list its names; require all.names=T to get dot-prefixed names
## [1] ".->age"       ".->name"      ".refClassDef" ".self"        "age"          "field"
## [7] "getClass"     "name"         "show"
x@.xData$.self; ## .self pseudo-field points back to the self object
## Reference class object of class "MyObject"
## Field "name":
## character(0)
## Field "age":
## numeric(0)

所以解决方案是:

MyObject <- setRefClass("MyObject",
    fields = list(name = "character", age = "numeric"),
    methods = list(
        getPrinter = function() {
            MyPrinter$new(obj=.self)
        }
    )
)