多段の継承

R における S3 と R6 を使ったオブジェクト指向プログラミング

Richie Cotton

Data Evangelist at DataCamp

ch4_3-multiple-levels-of-inheritance.003.png

R における S3 と R6 を使ったオブジェクト指向プログラミング

ch4_3-multiple-levels-of-inheritance.005.png

R における S3 と R6 を使ったオブジェクト指向プログラミング

ch4_3-multiple-levels-of-inheritance.006.png

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...