类别太多

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

Richie Cotton

Data Evangelist at DataCamp

x <- c(1, 3, 6, 10, 15)

class(x) <- c( "triangular_numbers", "natural_numbers", "numeric" )
R 中的 S3 与 R6 面向对象编程
is.numeric(x)
TRUE
is.triangular_numbers(x)
Error: could not find function "is.triangular_numbers"
R 中的 S3 与 R6 面向对象编程
inherits(x, "triangular_numbers")
TRUE
inherits(x, "natural_numbers")
TRUE
inherits(x, "numeric")
TRUE
R 中的 S3 与 R6 面向对象编程
what_am_i <- function(x, ...) {
  UseMethod("what_am_i")
}
R 中的 S3 与 R6 面向对象编程
what_am_i.triangular_numbers <- function(x, ...) {
  message("I'm triangular numbers")
  NextMethod("what_am_i")
}
what_am_i.natural_numbers <- function(x, ...) {
  message("I'm natural numbers")
  NextMethod("what_am_i")
}
what_am_i.numeric <- function(x, ...) {
  message("I'm numeric")
}
R 中的 S3 与 R6 面向对象编程
what_am_i(x)
I'm triangular numbers
I'm natural numbers
I'm numeric

ch2_4-too-much-class.017.png

R 中的 S3 与 R6 面向对象编程
what_am_i(x)
I'm triangular numbers
I'm natural numbers
I'm numeric

ch2_4-too-much-class.018.png

R 中的 S3 与 R6 面向对象编程
what_am_i(x)
I'm triangular numbers
I'm natural numbers
I'm numeric

ch2_4-too-much-class.019.png

R 中的 S3 与 R6 面向对象编程
what_am_i(x)
I'm triangular numbers
I'm natural numbers
I'm numeric

ch2_4-too-much-class.020.png

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

小结

  • 允许多个类
  • inherits() 测试任意类
  • NextMethod() 串联方法调用
R 中的 S3 与 R6 面向对象编程

Vamos praticar!

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

Preparing Video For Download...