Multiples niveaux d'héritage

Programmation orientée objet avec S3 et R6 en R

Richie Cotton

Data Evangelist at DataCamp

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

Programmation orientée objet avec S3 et R6 en R

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

Programmation orientée objet avec S3 et R6 en R

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

Programmation orientée objet avec S3 et R6 en R

 

thing_factory <- R6Class(
  "Thing"
)
child_thing_factory <- R6Class(
  "ChildThing",
  inherit = thing_factory
)
grand_child_thing_factory <- R6Class(
  "GrandChildThing",
  inherit = child_thing_factory
)
Programmation orientée objet avec S3 et R6 en R

 

thing_factory <- R6Class(
  "Thing",

public = list( do_something = function() { message("the parent do_something method") } )
)
Programmation orientée objet avec S3 et R6 en R

 

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

public = list( do_something = function() { message("the child do_something method") } )
)
Programmation orientée objet avec S3 et R6 en 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()
} ) )
Programmation orientée objet avec S3 et R6 en 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
Programmation orientée objet avec S3 et R6 en 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 )
)
Programmation orientée objet avec S3 et R6 en 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()
} ) )
Programmation orientée objet avec S3 et R6 en 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
Programmation orientée objet avec S3 et R6 en R

Résumé

  • Les objets R6 ne peuvent accéder qu'à leur parent direct
  • Les classes intermédiaires peuvent exposer leur parent
  • Utilisez une liaison active nommée super_
  • super_ doit simplement retourner super
Programmation orientée objet avec S3 et R6 en R

Passons à la pratique !

Programmation orientée objet avec S3 et R6 en R

Preparing Video For Download...