【问题标题】:The equivalent of 'this' or 'self' in R相当于 R 中的 'this' 或 'self'
【发布时间】:2016-07-19 00:49:12
【问题描述】:

我正在寻找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 中有一种很好的面向对象的方式来执行此操作。谢谢

【问题讨论】:

  • 这是一个“参考类”(?ReferenceClasses?setRefClass),而不是 S4 类本身(?Classes?Methods)。来自 ?ReferenceClasses,请参阅 .self

标签: r oop reference-class


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 2012-06-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-05
    • 2011-01-11
    • 1970-01-01
    • 2020-09-02
    相关资源
    最近更新 更多