2012-01-20 37 views

回答

12

這裏是一個例子:

setClass("yyy", representation(v="numeric")) 

setMethod("+", signature(e1 = "yyy", e2 = "yyy"), function (e1, e2) [email protected] + [email protected]) 
setMethod("+", signature(e1 = "yyy", e2 = "numeric"), function (e1, e2) [email protected] + e2) 

然後,

> y1 <- new("yyy", v = 1) 
> y2 <- new("yyy", v = 2) 
> 
> y1 + y2 
[1] 3 
> y1 + 3 
[1] 4 
+0

這只是完美的(和非常優雅)感謝 – RockScience

16

+運算符是ARITH組通用的(見?GroupGenericFunctions)因此可以實現該組中的所有功能與

的一部分
setMethod("Arith", "yyy", function(e1, e2) { 
    v = callGeneric([email protected], [email protected]) 
    new("yyy", v = v) 
}) 

然後用

setClass("yyy", representation(v="numeric")) 
setMethod(show, "yyy", function(object) { 
    cat("class:", class(object), "\n") 
    cat("v:", [email protected], "\n") 
}) 
setMethod("Arith", "yyy", function(e1, e2) { 
    v = callGeneric([email protected], [email protected]) 
    new("yyy", v = v) 
}) 

一會還要

> y1 = new("yyy", v=1) 
> y2 = new("yyy", v=2) 
> y1 + y2 
class: yyy 
v: 3 
> y1/y2 
class: yyy 
v: 0.5 
## ...and so on 
+0

是,這假設要+操作適用於對象的所有插槽? – RockScience

+1

它將重新派發給算術運算符,用於對象e1和e2的槽'v'。如果有插槽v和w,則可以寫入方法體new(「yyy」,v = callGeneric(e1 @ v,e2 @ v),w = callGeneric(e1 @ w,e2 @ w)) ' –