相当于R中的'this'或'self'

时间:2016-07-19 00:49:12

标签: r oop reference-class

我在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中做一个很好的面向对象的方法来做这个操作。谢谢

1 个答案:

答案 0 :(得分:7)

引用类(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)
        }
    )
)