On Mon, 27 Aug 2007, Faheem Mitha wrote:

>
> Just wondered about this curious behaviour. I'm trying to learn about
> classes. Basically setMethod works the first time, but does not seem to
> work the second time.
>                                                                 Faheem.
> *************************************************************************
> setClass("foo", representation(x="numeric"))
>
> bar <- function(object)
>   {
>     return(0)
>   }
>
> bar.foo <- function(object)
>   {
>     print([EMAIL PROTECTED])
>   }
> setMethod("bar", "foo", bar.foo)
>
> bar(f)
>
> # bar(f) gives 1.

Not for me. It gives
> bar(f)
Error: object "f" not found
Error in bar(f) : error in evaluating the argument 'object' in selecting a
method for function 'bar'

However, if I do
f = new("foo", x= 1)
first, it gives 1.

> bar <- function(object)
>   {
>     return(0)
>   }

Here you have masked the generic bar() with a new function bar(). Redefining 
bar() is the problem, not the second setMethod().

> bar.foo <- function(object)
>   {
>     print([EMAIL PROTECTED])
>   }
> setMethod("bar", "foo", bar.foo)

Because there was a generic bar(), even though it is overwritten by the new 
bar(), setMethod() doesn't automatically create another generic.

> f = new("foo", x= 1)
>
> bar(f)
>
> # bar(f) gives 0, not 1.
>

Because bar() isn't a generic function
> bar
function(object)
   {
     return(0)
   }


If you had used setGeneric() before setMethod(), as recommended, your example 
would have done what you expected, but it would still have wiped out any 
previous methods for bar() -- eg, try
  setMethod("bar","baz", function(object) print("baz"))
before you redefine bar(), and notice that getMethod("bar","baz") no longer 
finds it.



    -thomas

Thomas Lumley                   Assoc. Professor, Biostatistics
[EMAIL PROTECTED]       University of Washington, Seattle

______________________________________________
R-help@stat.math.ethz.ch mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.

Reply via email to