用繼承傳遞功能

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

Richie Cotton

Data Evangelist at DataCamp

以繼承傳遞功能示意圖

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

 

thing_factory <- R6Class(
  "Thing",
  private = list(
    a_field = "a value",
    another_field = 123
  ),
  public = list(
    do_something = function(x, y, z) {
      # do something here
    }
  )
)
在 R 中使用 S3 與 R6 的物件導向程式設計

父類別

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

 

child_thing_factory <- R6Class(
  "ChildThing",
  inherit = thing_factory

public = list( do_something_else = function() { # more functionality } )
)
在 R 中使用 S3 與 R6 的物件導向程式設計

子類別

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

父子關係

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

父子關係

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

 

a_thing <- thing_factory$new()

class(a_thing)
"Thing" "R6"  
inherits(a_thing, "Thing")
TRUE
inherits(a_thing, "R6")
TRUE
在 R 中使用 S3 與 R6 的物件導向程式設計
a_child_thing <- child_thing_factory$new()

class(a_child_thing)
"ChildThing" "Thing"      "R6"      
inherits(a_child_thing, "ChildThing")
TRUE
inherits(a_child_thing, "Thing")
TRUE
inherits(a_child_thing, "R6")
TRUE
在 R 中使用 S3 與 R6 的物件導向程式設計

重點整理

  • 繼承 來「傳遞功能」
  • R6Class() 使用 inherit 參數
  • 子類別會擁有父類別的功能
  • 反過來不成立
在 R 中使用 S3 與 R6 的物件導向程式設計

一起來練習吧!

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

Preparing Video For Download...