擁抱、擴充、覆寫

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

Richie Cotton

Data Evangelist at DataCamp

在 R 中使用 S3 與 R6 的物件導向程式設計
thing_factory <- R6Class(
  "Thing",
  public = list(
    do_something = function() {
      message("the parent do_something method")
    }
  )
)
在 R 中使用 S3 與 R6 的物件導向程式設計
child_thing_factory <- R6Class(
  "ChildThing",
  inherit = thing_factory,

public = list( do_something = function() { message("the child do_something method") },
do_something_else = function() { message("the child do_something_else method") }
)
)
在 R 中使用 S3 與 R6 的物件導向程式設計
a_child_thing <- child_thing_factory$new()
a_child_thing$do_something()
the child do_something method
在 R 中使用 S3 與 R6 的物件導向程式設計

 

 

private$ 存取「private」欄位

self$ 存取「self」中的「public」方法

super$ 存取「parent」中的「public」方法

在 R 中使用 S3 與 R6 的物件導向程式設計
child_thing_factory <- R6Class(
  "ChildThing",
  inherit = thing_factory,
  public = list(
    do_something = function() {
      message("the child do_something method")
    },
    do_something_else = function() {
      message("the child do_something_else method")

self$do_something()
super$do_something()
} ) )
在 R 中使用 S3 與 R6 的物件導向程式設計

 

a_child_thing <- child_thing_factory$new()
a_child_thing$do_something_else()
the child do_something_else method
the child do_something method
the parent do_something method
在 R 中使用 S3 與 R6 的物件導向程式設計

重點整理

  • 以「相同名稱」進行「覆寫」
  • 以「新名稱」進行「擴充」
  • self$ 存取「self」中的「public」方法
  • super$ 存取「parent」中的「public」方法
在 R 中使用 S3 與 R6 的物件導向程式設計

一起來練習吧!

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

Preparing Video For Download...