我有一个简单的 R6 对象生成器:
thing <- R6Class("youngThing",
private = list(
..age = 0),
active = list(
age = function(){
private$..age <- private$..age + 1
private$..age
}
)
)
这给了我一个简单的 R6 对象,其中 ..age
每次激活 age
时增加 1字段被称为:a_thing <- thing$new()
a_thing$age
# [1] 1
给定私有(private)字段 ..age
的阈值,我希望 a_thing 的对象类发生变化, 像这样:class(a_thing)
# [1] "youngThing" "R6"
for(timestep in 1:10){
if(a_thing$age >5 & ! inherits(a_thing, "olderThing")){
class(a_thing) <- c("olderThing", class(a_thing))
}
}
class(a_thing)
# [1] "olderThing" "youngThing" "R6"
但是,我希望这发生在对象内。有没有办法将此作为对象生成器中的事件绑定(bind)包含在内,以便从它创建的任何对象都将内置此功能?注意。最好将阈值类添加到对象中;它不会取代现有的类。
最佳答案
您可以更改 self
的类别.
library(R6)
thing <- R6Class(
"youngThing",
private = list(..age = 0),
active = list(
age = function() {
private$..age <- private$..age + 1
if(private$..age > 5 && !inherits(self, "olderThing")){
class(self) <- c("olderThing", class(self))
}
private$..age
}
)
)
a_thing
在 age <= 5
时有它的原始类.a_thing <- thing$new()
a_thing$age; a_thing$age; a_thing$age; a_thing$age; a_thing$age
#> [1] 2
#> [1] 3
#> [1] 4
#> [1] 5
class(a_thing)
#> [1] "youngThing" "R6"
然后它会在超过 5
时更新.a_thing$age
#> [1] 6
class(a_thing)
#> [1] "olderThing" "youngThing" "R6"
关于R:在对象生成器中使用事件绑定(bind)有条件地向 R6 对象添加新类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64597394/