Vários níveis de herança

Programação Orientada a Objetos com S3 e R6 em R

Richie Cotton

Data Evangelist at DataCamp

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

Programação Orientada a Objetos com S3 e R6 em R

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

Programação Orientada a Objetos com S3 e R6 em R

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

Programação Orientada a Objetos com S3 e R6 em R

 

thing_factory <- R6Class(
  "Thing"
)
child_thing_factory <- R6Class(
  "ChildThing",
  inherit = thing_factory
)
grand_child_thing_factory <- R6Class(
  "GrandChildThing",
  inherit = child_thing_factory
)
Programação Orientada a Objetos com S3 e R6 em R

 

thing_factory <- R6Class(
  "Thing",

public = list( do_something = function() { message("the parent do_something method") } )
)
Programação Orientada a Objetos com S3 e R6 em R

 

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

public = list( do_something = function() { message("the child do_something method") } )
)
Programação Orientada a Objetos com S3 e R6 em 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()
} ) )
Programação Orientada a Objetos com S3 e R6 em 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
Programação Orientada a Objetos com S3 e R6 em 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 )
)
Programação Orientada a Objetos com S3 e R6 em 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()
} ) )
Programação Orientada a Objetos com S3 e R6 em 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
Programação Orientada a Objetos com S3 e R6 em R

Resumo

  • Objetos R6acessam seu pai direto
  • Classes intermediárias podem expor seu pai
  • Use um vínculo ativo chamado super_
  • super_ deve apenas retornar super
Programação Orientada a Objetos com S3 e R6 em R

Vamos praticar!

Programação Orientada a Objetos com S3 e R6 em R

Preparing Video For Download...