简体   繁体   中英

Generic functions on objects with multiple classes

I am interested to write a generic method that behaves based on multiple class type of the same object. For example, say we have the following:

redApple <- function(){
 structure(list(), class = c("apple", "red"))
}

greenApple <- function(){
 structure(list(), class = c("apple", "green"))
}

eat <- function(x)UseMethod("eat")
eat.apple <- function(x)  print("Eating apple")

color <- function(x) UseMethod("color")
color.red <- function(x) print("my food is red")
color.green <- function(x) print("my food is green")

Now we create the following objects:

obj1 <- redApple()
obj2 <- greenApple()

Here color(obj1) prints my food is red and color(obj2) prints my food is green , while both eat(obj1) and eat(obj2) print Eating apple .

Now I'd like my generic function behave differently for obj1 and obj2 . For example I'd like eat(obj1) to print Eating red apple and eat(obj2) to print Eating green apple

You can check for the class of the object passed to the function and make cases accordingly:

eat.apple <- function(x)  
{
  if("green" %in% class(x)) print("Eating green apple")
  else if("red" %in% class(x)) print("Eating red apple")
  else print("Eating generic apple!")
}

##addition

eat.green <- function(x)  
{
  print("Eating green apple")
}

eat.red <- function(x)  
{
  print("Eating red apple")
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM