gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 14:41:18 25 4
gpt4 key购买 nike

我在 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com