Suprascriere, extindere, moștenire

Programare orientată pe obiecte cu S3 și R6 în R

Richie Cotton

Data Evangelist at DataCamp

Programare orientată pe obiecte cu S3 și R6 în R
thing_factory <- R6Class(
  "Thing",
  public = list(
    do_something = function() {
      message("the parent do_something method")
    }
  )
)
Programare orientată pe obiecte cu S3 și R6 în R
child_thing_factory <- R6Class(
  "ChildThing",
  inherit = thing_factory,

public = list( do_something = function() { message("the child do_something method") },
do_something_else = function() { message("the child do_something_else method") }
)
)
Programare orientată pe obiecte cu S3 și R6 în R
a_child_thing <- child_thing_factory$new()
a_child_thing$do_something()
the child do_something method
Programare orientată pe obiecte cu S3 și R6 în R

 

 

private$ accesează câmpurile private

self$ accesează metodele publice din self

super$ accesează metodele publice din părinte

Programare orientată pe obiecte cu S3 și R6 în R
child_thing_factory <- R6Class(
  "ChildThing",
  inherit = thing_factory,
  public = list(
    do_something = function() {
      message("the child do_something method")
    },
    do_something_else = function() {
      message("the child do_something_else method")

self$do_something()
super$do_something()
} ) )
Programare orientată pe obiecte cu S3 și R6 în R

 

a_child_thing <- child_thing_factory$new()
a_child_thing$do_something_else()
the child do_something_else method
the child do_something method
the parent do_something method
Programare orientată pe obiecte cu S3 și R6 în R

Rezumat

  • Suprascriere prin același nume
  • Extindere printr-un nume nou
  • self$ accesează metodele publice din self
  • super$ accesează metodele publice din părinte
Programare orientată pe obiecte cu S3 și R6 în R

Să exersăm!

Programare orientată pe obiecte cu S3 și R6 în R

Preparing Video For Download...