Vícenásobné úrovně dědičnosti

Objektově orientované programování s S3 a R6 v R

Richie Cotton

Data Evangelist at DataCamp

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

Objektově orientované programování s S3 a R6 v R

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

Objektově orientované programování s S3 a R6 v R

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

Objektově orientované programování s S3 a R6 v R

 

thing_factory <- R6Class(
  "Thing"
)
child_thing_factory <- R6Class(
  "ChildThing",
  inherit = thing_factory
)
grand_child_thing_factory <- R6Class(
  "GrandChildThing",
  inherit = child_thing_factory
)
Objektově orientované programování s S3 a R6 v R

 

thing_factory <- R6Class(
  "Thing",

public = list( do_something = function() { message("the parent do_something method") } )
)
Objektově orientované programování s S3 a R6 v R

 

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

public = list( do_something = function() { message("the child do_something method") } )
)
Objektově orientované programování s S3 a R6 v R

 

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()
} ) )
Objektově orientované programování s S3 a R6 v R

 

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
Objektově orientované programování s S3 a R6 v R

 

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

active = list( super_ = function() super )
)
Objektově orientované programování s S3 a R6 v R

 

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()
} ) )
Objektově orientované programování s S3 a R6 v R

 

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
Objektově orientované programování s S3 a R6 v R

Shrnutí

  • R6 objekty mají přístup pouze k přímému rodiči
  • Mezilehlé třídy mohou zpřístupnit svého rodiče
  • Použijte aktivní vazbu s názvem super_
  • super_ má jednoduše vracet super
Objektově orientované programování s S3 a R6 v R

Pojďme si procvičit!

Objektově orientované programování s S3 a R6 v R

Preparing Video For Download...