Skip to content

S4 initialize methods, unexpected recursive callNextMethod

4 messages · Seth Falcon, John Chambers

#
Hi,

Given a simple three class hierarchy: A <-- B <-- C

I want to define an initialize method for each class such that when I
call new("C", x=5), the initialize methods for A and B are used to
incrementally build the object.

When I do what seems obvious to me using callNextMethod, I get an
infinite recursion.  An example follows...

setClass("A", representation(a="numeric"))
setClass("B", representation(b="numeric"), contains="A")
setClass("C", representation(c="numeric"), contains="B")

setMethod("initialize", signature(.Object="A"),
          function(.Object, x) {
              cat("in A\n")
              .Object at a <- x
              .Object
          })

setMethod("initialize", signature(.Object="B"),
          function(.Object, x) {
              cat("in B\n")
              .Object <- callNextMethod(.Object=.Object, x=x)
              .Object at b <- .Object at a + 1
              .Object
          })

setMethod("initialize", signature(.Object="C"),
          function(.Object, x) {
              cat("in C\n")
              .Object <- callNextMethod(.Object=.Object, x=x)
              .Object at c <- .Object at a + .Object at b + 1
              .Object
          })


## Works as I am expecting for B
in B
in A

## When you create a C, the B method gets called but the appropriate
## next method info seems lost and we end up back in C's method ?!
in C
in B
in C
in B
in C
  C-c C-c

Should this work?  Is there a better way to organize the initializers
for a simple hierarchy (perhaps assume that args to the initializers
are not the same for A, B, and C).

Thanks,

+ seth
#
John Chambers <jmc at r-project.org> writes:
Thanks for the explanation and work around suggestion.  If I'm feeling
brave, perhaps I'll take a look at the addNextMethod and
callNextMethod computations.  We found this bug for a "real" use-case,
so I have some interest in a solution that doesn't involve changing
the initializers for the three classes involved...

Best,

+ seth
1 day later