[英]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
. 这里的color(obj1)
打印my food is red
和color(obj2)
打印my food is green
,而两个eat(obj1)
和eat(obj2)
打印Eating apple
。
Now I'd like my generic function behave differently for obj1
and obj2
. 现在我想我的泛型函数对obj1
和obj2
行为有所不同。 For example I'd like eat(obj1)
to print Eating red apple
and eat(obj2)
to print Eating green apple
例如,我喜欢eat(obj1)
打印Eating red apple
和eat(obj2)
打印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")
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.