Zbyt wiele klas

Programowanie obiektowe z S3 i R6 w R

Richie Cotton

Data Evangelist at DataCamp

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

class(x) <- c( "triangular_numbers", "natural_numbers", "numeric" )
Programowanie obiektowe z S3 i R6 w R
is.numeric(x)
TRUE
is.triangular_numbers(x)
Error: could not find function "is.triangular_numbers"
Programowanie obiektowe z S3 i R6 w R
inherits(x, "triangular_numbers")
TRUE
inherits(x, "natural_numbers")
TRUE
inherits(x, "numeric")
TRUE
Programowanie obiektowe z S3 i R6 w R
what_am_i <- function(x, ...) {
  UseMethod("what_am_i")
}
Programowanie obiektowe z S3 i R6 w R
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")
}
Programowanie obiektowe z S3 i R6 w R
what_am_i(x)
I'm triangular numbers
I'm natural numbers
I'm numeric

ch2_4-too-much-class.017.png

Programowanie obiektowe z S3 i R6 w R
what_am_i(x)
I'm triangular numbers
I'm natural numbers
I'm numeric

ch2_4-too-much-class.018.png

Programowanie obiektowe z S3 i R6 w R
what_am_i(x)
I'm triangular numbers
I'm natural numbers
I'm numeric

ch2_4-too-much-class.019.png

Programowanie obiektowe z S3 i R6 w R
what_am_i(x)
I'm triangular numbers
I'm natural numbers
I'm numeric

ch2_4-too-much-class.020.png

Programowanie obiektowe z S3 i R6 w R

Podsumowanie

  • Dozwolone są wielokrotne klasy
  • inherits() testuje dowolne klasy
  • NextMethod() łączy wywołania metod
Programowanie obiektowe z S3 i R6 w R

Czas na ćwiczenia!

Programowanie obiektowe z S3 i R6 w R

Preparing Video For Download...