Читать книгу The Big R-Book - Philippe J. S. De Brouwer - Страница 192

6.2.3 Method Dispatch

Оглавление

So in S3, it is not the object that has to know how a call to it has to be handled, but it is the generic function5 that gets the call and has to dispatch it.

The way this works in R is by calling UseMethod() in the dispatching function. This creates a vector of function names, like

UseMethod()

paste0(“generic”, “.”, c(class(x), “default”))

and dispatches to the most specific handling function available. The default class is the last in the list and is the last resort: if R does not find a class specific method it will call the default action.

Beneath you can see this in action:

# probe # Dispatcher function # Arguments: # x -- account object # Returns # confirmation of object type probe <- function(x) UseMethod(“probe”) # probe.account # action for account object for dispatcher function probe() # Arguments: # x -- account object # Returns # confirmation of object “account” probe.account <- function(x) “This is a bank account” # probe.default # action if an incorrect object type is provided to probe() # Arguments: # x -- account object # Returns # error message probe.default <- function(x) “Sorry. Unknown class” probe (structure(list(), class = “account”)) ## [1] “This is a bank account” # No method for class ‘customer’, fallback to ‘account’ probe(structure(list(), class = c(“customer”, “account”))) ## [1] “This is a bank account” # No method for class ‘customer’, so falls back to default probe(structure(list(), class = “customer”)) ## [1] “Sorry. Unknown class” probe(df) # fallback to default for data.frame ## [1] “Sorry. Unknown class” probe.account(df) # force R to use the account method ## [1] “This is a bank account” my_curr_acc <- account(“Philippe”, 150) # real account probe(my_curr_acc) ## [1] “This is a bank account”

The Big R-Book

Подняться наверх