複製 R6 物件

在 R 中使用 S3 與 R6 的物件導向程式設計

Richie Cotton

Data Evangelist at DataCamp

 

 

  • 環境是以參照複製
  • R6 物件也是如此
在 R 中使用 S3 與 R6 的物件導向程式設計

 

thing_factory <- R6Class(
  "Thing",

private = list( ..a_field = 123 ),
active = list( a_field = function(value) { if(missing(value)) { private$..a_field } else { private$..a_field <- value } } )
)
在 R 中使用 S3 與 R6 的物件導向程式設計

 

a_thing <- thing_factory$new()
a_copy <- a_thing

a_thing$a_field <- 456
a_copy$a_field
456
在 R 中使用 S3 與 R6 的物件導向程式設計

 

 

 

clone() 以值複製

在 R 中使用 S3 與 R6 的物件導向程式設計

 

a_clone <- a_thing$clone()
a_thing$a_field <- 789
a_clone$a_field
456
在 R 中使用 S3 與 R6 的物件導向程式設計

 

container_factory <- R6Class(
  "Container",

private = list( ..thing = thing_factory$new() ),
active = list( thing = function(value) { if(missing(value)) { private$..thing } else { private$..thing <- value } } )
)
在 R 中使用 S3 與 R6 的物件導向程式設計

 

a_container <- container_factory$new()
a_clone <- a_container$clone()
a_container$thing$a_field <- "a new value" 
a_clone$thing$a_field
"a new value"
在 R 中使用 S3 與 R6 的物件導向程式設計

 

a_deep_clone <- a_container$clone(deep = TRUE)
a_container$thing$a_field <- "a different value" 
a_deep_clone$thing$a_field
"a new value"
在 R 中使用 S3 與 R6 的物件導向程式設計

重點整理

  • R6 物件以「參照」複製
  • clone() 以「值」複製
  • clone() 會自動產生
  • clone(deep = TRUE) 用於 R6 欄位
在 R 中使用 S3 與 R6 的物件導向程式設計

一起來練習吧!

在 R 中使用 S3 與 R6 的物件導向程式設計

Preparing Video For Download...