使用主動繫結的讀寫

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

Richie Cotton

Data Evangelist at DataCamp

第 3 章:使用主動繫結的讀寫.003.png

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

 

 

     讀取 = 讀出資料欄位

     設定 = 寫入資料欄位

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

主動繫結(Active Bindings)

 

 

     定義像函式

     存取像資料變數

在 R 中使用 S3 與 R6 的物件導向程式設計
thing_factory <- R6Class(
  "Thing",
  private = list(
    ..a_field = "a value",
    ..another_field = 123
  ),
  active = list(

a_field = function() {
if(is.na(private$..a_field)) { return("a missing value") }
private$..a_field
},
another_field = function(value) {
if(missing(value)) { private$..another_field } else {
assert_is_a_number(value)
private$..another_field <- value }
}
) )
在 R 中使用 S3 與 R6 的物件導向程式設計
a_thing <- thing_factory$new()

a_thing$a_field
"a value"
a_thing$a_field <- "a new value"
Error in (function (value)  : a_field is read-only.
在 R 中使用 S3 與 R6 的物件導向程式設計

 

a_thing$another_field <- 456
a_thing$another_field <- "456"
Error in (function (value) : is_a_number : 
value is not of class 'numeric'; it has class 'character'.
在 R 中使用 S3 與 R6 的物件導向程式設計

重點整理

  • 以「主動繫結」控制私有存取
  • 定義方式像「函式」
  • 存取方式像「資料」
在 R 中使用 S3 與 R6 的物件導向程式設計

一起來練習吧!

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

Preparing Video For Download...