具有多个类的对象的泛型函数

时间:2019-04-01 08:11:33

标签: r

我有兴趣编写一个基于同一对象的多个类类型运行的通用方法。例如,假设我们有以下内容:

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")

现在我们创建以下对象:

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

这里color(obj1)打印my food is redcolor(obj2)打印my food is green,而eat(obj1)eat(obj2)都打印Eating apple

现在,我希望我的泛型函数对obj1obj2的行为有所不同。例如,我希望eat(obj1)打印Eating red apple,而eat(obj2)打印Eating green apple

1 个答案:

答案 0 :(得分:0)

您可以检查传递给该函数的对象的类并相应地进行大小写:

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")
}