Multiple Levels of Inheritance

Object-Oriented Programming with S3 and R6 in R

Richie Cotton

Data Evangelist at DataCamp

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

Object-Oriented Programming with S3 and R6 in R

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

Object-Oriented Programming with S3 and R6 in R

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

Object-Oriented Programming with S3 and R6 in R

 

thing_factory <- R6Class(
  "Thing"
)
child_thing_factory <- R6Class(
  "ChildThing",
  inherit = thing_factory
)
grand_child_thing_factory <- R6Class(
  "GrandChildThing",
  inherit = child_thing_factory
)
Object-Oriented Programming with S3 and R6 in R

 

thing_factory <- R6Class(
  "Thing",

public = list( do_something = function() { message("the parent do_something method") } )
)
Object-Oriented Programming with S3 and R6 in R

 

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

public = list( do_something = function() { message("the child do_something method") } )
)
Object-Oriented Programming with S3 and R6 in 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()
} ) )
Object-Oriented Programming with S3 and R6 in 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
Object-Oriented Programming with S3 and R6 in 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 )
)
Object-Oriented Programming with S3 and R6 in 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()
} ) )
Object-Oriented Programming with S3 and R6 in 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
Object-Oriented Programming with S3 and R6 in R

Summary

  • R6 objects can only access their direct parent
  • Intermediate classes can expose their parent
  • Use an active binding named super_
  • super_ should simply return super
Object-Oriented Programming with S3 and R6 in R

Let's practice!

Object-Oriented Programming with S3 and R6 in R

Preparing Video For Download...