R:在对象生成器中使用主动绑定有条件地将新类添加到 R6 对象

jay*_*ayb 4 oop inheritance r r6

我有一个简单的 R6 对象生成器:

thing <- R6Class("youngThing",
                 private = list(
                   ..age = 0),
                 active = list(
                   age = function(){
                     private$..age <- private$..age + 1
                     private$..age
                   }
                 )
)
Run Code Online (Sandbox Code Playgroud)

这给了我一个简单的 R6 对象,..age每次age调用活动字段时它都会增加 1:

a_thing <- thing$new()

a_thing$age
# [1] 1
Run Code Online (Sandbox Code Playgroud)

我希望 a_thing 的对象类在给定私有字段的阈值的情况下进行更改..age,如下所示:

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" 
Run Code Online (Sandbox Code Playgroud)

但是,我希望这发生在对象内。有没有办法将其作为活动绑定包含在对象生成器中,以便从它创建的任何对象都将内置此功能?

注意。优选地,将阈值类别添加到对象中;它不会取代现有的类。

Pau*_*aul 5

您可以更改 的类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
    }
  )
)
Run Code Online (Sandbox Code Playgroud)

a_thing有它原来的类 while 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" 
Run Code Online (Sandbox Code Playgroud)

然后一旦结束就会更新5

a_thing$age
#> [1] 6

class(a_thing)
#> [1] "olderThing" "youngThing" "R6" 
Run Code Online (Sandbox Code Playgroud)