[R] Understanding S4 method dispatch

Hervé Pagès hpages at fhcrc.org
Wed Aug 14 20:50:52 CEST 2013


And it doesn't even select "the first method lexicographically in the
ordering" (whatever that means):

   setClass("B", "NULL")
   setClass("A", "NULL")
   setMethod("show", "B", function(object) cat("B object\n"))
   setMethod("show", "A", function(object) cat("A object\n"))

   setClass("AB", contains=c("B", "A"))
   ab <- new("AB")

Then:

   > ab
   B object

   > is(ab)
   [1] "AB"               "B"                "A"                ".NULL" 

   [5] "NULL"             "OptionalFunction" "optionalMethod"

So the order of the superclasses passed to 'contains' seems to
actually matter (even though I don't remember I've seen this
documented anywhere). Is it correct to speculate that, if the
distance is the same, and if the tie cannot be broken by looking
at whether one class involved in the tie extends the other one,
then the order in which the superclasses were passed to 'contains'
is looked at?

Last but not least, if you try to redefine class AB by switching
A and B in 'contains' again, it seems to have no effect:

   > setClass("AB", contains=c("A", "B"))
   > ab
   B object

except that now this contradicts is():

   > is(ab)
   [1] "AB"               "A"                "B"                ".NULL" 

   [5] "NULL"             "OptionalFunction" "optionalMethod"

I'm just going to stop trying to sort this mess out :-/

H.

On 08/14/2013 09:54 AM, Hadley Wickham wrote:
> On Wed, Aug 14, 2013 at 11:36 AM, Simon Zehnder <szehnder at uni-bonn.de> wrote:
>> Because the signature is always (A,A) or (B,B). Then, as in AB we have A and B and no relationship between A and B, R chooses the method lexicographically. The result is as expected: f for A is chosen.
>
> It's not as expected, because it doesn't give a message. From ?Methods:
>
> If there is no best match, the selection is ambiguous and a message is
> printed noting which method was selected (the first method
> lexicographically in the ordering) and what other methods could have
> been selected.
>
> Hadley
>

-- 
Hervé Pagès

Program in Computational Biology
Division of Public Health Sciences
Fred Hutchinson Cancer Research Center
1100 Fairview Ave. N, M1-B514
P.O. Box 19024
Seattle, WA 98109-1024

E-mail: hpages at fhcrc.org
Phone:  (206) 667-5791
Fax:    (206) 667-1319



More information about the R-help mailing list