[R] S4 base class
Martin Morgan
mtmorgan at fhcrc.org
Thu Oct 17 19:27:06 CEST 2013
On 10/17/2013 08:54 AM, Michael Meyer wrote:
> Suppose you have a base class "Base" which implements a function "Base::F"
> which works in most contexts but not in the context of "ComplicatedDerived" class
> where some preparation has to happen before this very same function can be called.
>
> You would then define
>
> void ComplicatedDerived::F(...){
>
> preparation();
> Base::F();
> }
>
> You can nealry duplicate this in R via
>
> setMethod("F",
> signature(this="ComplicatedDerived"),
> definition=function(this){
>
> preparation(this)
> F(as(this,"Base"))
> })
>
> but it will fail whenever F uses virtual functions (i.e. generics) which are only defined
> for derived classes of Base
With
.A <- setClass("A", representation(a="numeric"))
.B <- setClass("B", representation(b="numeric"), contains="A")
setGeneric("f", function(x, ...) standardGeneric("f"))
setMethod("f", "A", function(x, ...) {
message("f,A-method")
g(x, ...) # generic with methods only for derived classes
})
setMethod("f", "B", function(x, ...) {
message("f,B-method")
callNextMethod(x, ...) # earlier response from Duncan Murdoch
})
setGeneric("g", function(x, ...) standardGeneric("g"))
setMethod("g", "B", function(x, ...) {
message("g,B-method")
x
})
one has
> f(.B())
f,B-method
f,A-method
g,B-method
An object of class "B"
Slot "b":
numeric(0)
Slot "a":
numeric(0)
?
--
Computational Biology / Fred Hutchinson Cancer Research Center
1100 Fairview Ave. N.
PO Box 19024 Seattle, WA 98109
Location: Arnold Building M1 B861
Phone: (206) 667-2793
More information about the R-help
mailing list