继承、扩展、重写

R 中的 S3 与 R6 面向对象编程

Richie Cotton

Data Evangelist at DataCamp

R 中的 S3 与 R6 面向对象编程
thing_factory <- R6Class(
  "Thing",
  public = list(
    do_something = function() {
      message("the parent do_something method")
    }
  )
)
R 中的 S3 与 R6 面向对象编程
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") }
)
)
R 中的 S3 与 R6 面向对象编程
a_child_thing <- child_thing_factory$new()
a_child_thing$do_something()
the child do_something method
R 中的 S3 与 R6 面向对象编程

 

 

private$ 访问 私有 字段

self$ 访问 自身public 方法

super$ 访问 父类public 方法

R 中的 S3 与 R6 面向对象编程
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()
} ) )
R 中的 S3 与 R6 面向对象编程

 

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
R 中的 S3 与 R6 面向对象编程

总结

  • 通过使用相同名称进行重写
  • 通过使用新名称进行扩展
  • self$ 访问 自身public 方法
  • super$ 访问 父类public 方法
R 中的 S3 与 R6 面向对象编程

Vamos praticar!

R 中的 S3 与 R6 面向对象编程

Preparing Video For Download...