相当于 R 中的“this"或“self" [英] The equivalent of 'this' or 'self' in R

查看:60
本文介绍了相当于 R 中的“this"或“self"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在 R 中寻找与 python 的self"关键字或 java 的this"关键字等效的关键字.在下面的示例中,我正在从不同 S4 对象的方法中创建 S4 对象,并且需要将指针传递给我自己.语言中有什么东西可以帮助我做到这一点吗?

I am looking for the equivalent of python's 'self' keyword or java's 'this' keyword in R. In the following example I am making an S4 object from a method of a different S4 object and need to pass a pointer to myself. Is there something in the language to help me do this?

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 中做这个操作.谢谢

I can do this with a freestanding method but I was hoping for a nice object-oriented way of doing this operation in R. Thanks

推荐答案

引用类 (RC) 对象基本上是封装环境的 S4 对象.环境持有 RC 对象的字段,并被设置为其方法的封闭环境;这就是对字段标识符的非限定引用绑定到实例字段的方式.我能够在环境中找到一个 .self 对象,我认为这正是您正在寻找的对象.

Reference class (RC) objects are basically S4 objects that wrap an environment. The environment holds the fields of the RC object, and is set as the enclosing environment of its methods; that's how unqualified references to the field identifiers bind to the instance's fields. I was able to find a .self object sitting in the environment that I believe is exactly what you're looking for.

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)
        }
    )
)

这篇关于相当于 R 中的“this"或“self"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆