多層繼承

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

Richie Cotton

Data Evangelist at DataCamp

第 4 章第 3 節:多層繼承.003

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

第 4 章第 3 節:多層繼承.005

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

第 4 章第 3 節:多層繼承.006

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

 

thing_factory <- R6Class(
  "Thing"
)
child_thing_factory <- R6Class(
  "ChildThing",
  inherit = thing_factory
)
grand_child_thing_factory <- R6Class(
  "GrandChildThing",
  inherit = child_thing_factory
)
在 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") } )
)
在 R 中使用 S3 與 R6 的物件導向程式設計

 

grand_child_thing_factory <- R6Class(
  "GrandChildThing",
  inherit = child_thing_factory,
  public = list(
    do_something = function() {
      message("the grand-child do_something method")

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

 

a_grand_child_thing <- grand_child_thing_factory$new()

a_grand_child_thing$do_something()
the grand-child do_something method

the child do_something method
Error in a_grand_child_thing$do_something(): attempt to apply non-function
在 R 中使用 S3 與 R6 的物件導向程式設計

 

child_thing_factory <- R6Class(
  "ChildThing",
  inherit = thing_factory,
  public = list(
    do_something = function() {
      message("the child do_something method")
    }
  ),

active = list( super_ = function() super )
)
在 R 中使用 S3 與 R6 的物件導向程式設計

 

grand_child_thing_factory <- R6Class(
  "GrandChildThing",
  inherit = child_thing_factory,
  public = list(
    do_something = function() {
      message("the grand-child do_something method")

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

 

a_grand_child_thing <- grand_child_thing_factory$new()

a_grand_child_thing$do_something()
the grand-child do_something method
the child do_something method
the parent do_something method
在 R 中使用 S3 與 R6 的物件導向程式設計

重點回顧

  • R6 物件只能「存取直接父類
  • 中介類別可以「公開它的父類
  • 使用名為 super_ 的「主動繫結
  • super_ 應直接回傳 super
在 R 中使用 S3 與 R6 的物件導向程式設計

一起來練習吧!

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

Preparing Video For Download...