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

标签 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 中执行此操作。谢谢

最佳答案

引用类 (RC) 对象基本上是包装环境的 S4 对象。环境保存了 RC 对象的字段,并被设置为其方法的封闭环境;这就是对字段标识符的非限定引用如何绑定(bind)到实例的字段。我找到了 .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)
        }
    )
)

关于r - 相当于 R 中的 'this' 或 'self',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38447966/

相关文章:

处理向量的 R 函数

r - r中用逗号分割和重新排序字符串

有条件的 R 循环

r - 如何使用引用类在 R 的父类中设置字段?

r - R 中引用类的initialize() 方法中的自动分配

r - R引用类中有析构函数吗?

R geepack : unreasonably large estimates using GEE

oop - 知道何时对领域关系进行建模以及如何处理上下文关系

php - 如何给大量类方法 "almost"相同的代码

php - 我应该将仅在一个类方法中使用的变量保留在本地还是将它们声明为类属性?