Прийняти, розширити, перевизначити

Об'єктно-орієнтоване програмування з S3 та R6 в R

Richie Cotton

Data Evangelist at DataCamp

Об'єктно-орієнтоване програмування з S3 та R6 в R
thing_factory <- R6Class(
  "Thing",
  public = list(
    do_something = function() {
      message("the parent do_something method")
    }
  )
)
Об'єктно-орієнтоване програмування з S3 та R6 в 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") }
)
)
Об'єктно-орієнтоване програмування з S3 та R6 в R
a_child_thing <- child_thing_factory$new()
a_child_thing$do_something()
the child do_something method
Об'єктно-орієнтоване програмування з S3 та R6 в R

 

 

private$ звертається до полів private

self$ звертається до public-методів у self

super$ звертається до public-методів у parent

Об'єктно-орієнтоване програмування з S3 та R6 в 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()
} ) )
Об'єктно-орієнтоване програмування з S3 та R6 в 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
Об'єктно-орієнтоване програмування з S3 та R6 в R

Підсумок

  • Перевизначайте, надаючи те саме ім'я
  • Розширюйте, надаючи нове ім'я
  • self$ звертається до public-методів у self
  • super$ звертається до public-методів у parent
Об'єктно-орієнтоване програмування з S3 та R6 в R

Давайте потренуємось!

Об'єктно-орієнтоване програмування з S3 та R6 в R

Preparing Video For Download...