Rev 68948 | Blame | Compare with Previous | Last modification | View Log | Download | RSS feed
% File src/library/base/man/UseMethod.Rd% Part of the R package, https://www.R-project.org% Copyright 1995-2014 R Core Team% Distributed under GPL 2 or later\name{UseMethod}\title{Class Methods}\alias{UseMethod}\alias{NextMethod}\alias{S3Methods}\alias{.Method}\alias{.Generic}\alias{.Class}\description{\R possesses a simple generic function mechanism which can be used foran object-oriented style of programming. Method dispatch takes placebased on the class(es) of the first argument to the generic function or ofthe object supplied as an argument to \code{UseMethod} or \code{NextMethod}.}\usage{UseMethod(generic, object)NextMethod(generic = NULL, object = NULL, \dots)}\arguments{\item{generic}{a character string naming a function (and not abuilt-in operator). Required for \code{UseMethod}.}\item{object}{for \code{UseMethod}: an object whose class willdetermine the method to be dispatched. Defaults to the firstargument of the enclosing function.}\item{\dots}{further arguments to be passed to the next method.}}\details{An \R object is a data object which has a \code{class}attribute (and this can be tested by \code{\link{is.object}}).A class attribute is a character vector giving the names ofthe classes from which the object \emph{inherits}.If the object does not have a class attribute, it has an implicitclass. Matrices and arrays have class \code{"matrix"}or\code{"array"} followed by the class of the underlying vector.Most vectors have class the result of \code{\link{mode}(x)}, exceptthat integer vectors have class \code{c("integer", "numeric")} andreal vectors have class \code{c("double", "numeric")}.When a function calling \code{UseMethod("fun")} is applied to anobject with class attribute \code{c("first", "second")}, the systemsearches for a function called \code{fun.first} and, if it finds it,applies it to the object. If no such function is found a functioncalled \code{fun.second} is tried. If no class name produces asuitable function, the function \code{fun.default} is used, if itexists, or an error results.Function \code{\link{methods}} can be used to find out about themethods for a particular generic function or class.\code{UseMethod} is a primitive function but uses standard argumentmatching. It is not the only means of dispatch of methods, for thereare \link{internal generic} and \link{group generic} functions.\code{UseMethod} currently dispatches on the implicit class even forarguments that are not objects, but the other means of dispatch donot.\code{NextMethod} invokes the next method (determined by theclass vector, either of the object supplied to the generic, or ofthe first argument to the function containing \code{NextMethod} if amethod was invoked directly). Normally \code{NextMethod} is used withonly one argument, \code{generic}, but if further arguments aresupplied these modify the call to the next method.\code{NextMethod} should not be called except in methods called by\code{UseMethod} or from internal generics (see\link{InternalGenerics}). In particular it will not work insideanonymous calling functions (e.g., \code{get("print.ts")(AirPassengers)}).Namespaces can register methods for generic functions. To supportthis, \code{UseMethod} and \code{NextMethod} search for methods intwo places: first in the environment in which the generic functionis called, and then in the registration data base for theenvironment in which the generic is defined (typically a namespace).So methods for a generic function need to be available in theenvironment of the call to the generic, or they must be registered.(It does not matter whether they are visible in the environment inwhich the generic is defined.)}\section{Technical Details}{Now for some obscure details that need to appear somewhere. Thesecomments will be slightly different than those in Chambers(1992).(See also the draft \sQuote{R Language Definition}.)\code{UseMethod} creates a new function call witharguments matched as they came in to the generic. Any local variablesdefined before the call to \code{UseMethod} are retained (unlike S). Anystatements after the call to \code{UseMethod} will not be evaluated as\code{UseMethod} does not return. \code{UseMethod} can be called withmore than two arguments: a warning will be given and additionalarguments ignored. (They are not completely ignored in S.) If it iscalled with just one argument, the class of the first argument of theenclosing function is used as \code{object}: unlike S this is the firstactual argument passed and not the current value of the object of thatname.\code{NextMethod} works by creating a special call frame for the nextmethod. If no new arguments are supplied, the arguments will be thesame in number, order and name as those to the current method buttheir values will be promises to evaluate their name in the currentmethod and environment. Any named arguments matched to \code{\dots}are handled specially: they either replace existing arguments of thesame name or are appended to the argument list. They are passed on asthe promise that was supplied as an argument to the currentenvironment. (S does this differently!) If they have been evaluatedin the current (or a previous environment) they remain evaluated.(This is a complex area, and subject to change: see the draft\sQuote{R Language Definition}.)The search for methods for \code{NextMethod} is slightly differentfrom that for \code{UseMethod}. Finding no \code{fun.default} is notnecessarily an error, as the search continues to the genericitself. This is to pick up an \link{internal generic} like \code{[}which has no separate default method, and succeeds only if the genericis a \link{primitive} function or a wrapper for a\code{\link{.Internal}} function of the same name. (When a primitiveis called as the default method, argument matching may not work asdescribed above due to the different semantics of primitives.)You will see objects such as \code{.Generic}, \code{.Method}, and\code{.Class} used in methods. These are set in the environmentwithin which the method is evaluated by the dispatch mechanism, whichis as follows:\enumerate{\item Find the context for the calling function (the generic): thisgives us the unevaluated arguments for the original call.\item Evaluate the object (usually an argument) to be used fordispatch, and find a method (possibly the default method) or throwan error.\item Create an environment for evaluating the method and insertspecial variables (see below) into that environment. Also copy anyvariables in the environment of the generic that are not formal (oractual) arguments.\item Fix up the argument list to be the arguments of the callmatched to the formals of the method.}\code{.Generic} is a length-one character vector naming the generic function.\code{.Method} is a character vector (normally of length one) namingthe method function. (For functions in the group generic\code{\link[=S3groupGeneric]{Ops}} it is of length two.)\code{.Class} is a character vector of classes used to find the nextmethod. \code{NextMethod} adds an attribute \code{"previous"} to\code{.Class} giving the \code{.Class} last used for dispatch, andshifts \code{.Class} along to that used for dispatch.\code{.GenericCallEnv} and \code{.GenericDefEnv} are the environmentsof the call to be generic and defining the generic respectively. (Thelatter is used to find methods registered for the generic.)Note that \code{.Class} is set when the generic is called, and isunchanged if the class of the dispatching argument is changed in amethod. It is possible to change the method that \code{NextMethod}would dispatch by manipulating \code{.Class}, but \sQuote{this is notrecommended unless you understand the inheritance mechanismthoroughly} (Chambers & Hastie, 1992, p.\sspace{}469).}\note{This scheme is called \emph{S3} (S version 3). For new projects,it is recommended to use the more flexible and robust \emph{S4} schemeprovided in the \pkg{methods} package.}\seealso{The draft \sQuote{R Language Definition}.\code{\link{methods}}, \code{\link{class}},\code{\link{getS3method}}, \code{\link{is.object}}.}\references{Chambers, J. M. (1992)\emph{Classes and methods: object-oriented programming in S.}Appendix A of \emph{Statistical Models in S}eds J. M. Chambers and T. J. Hastie, Wadsworth & Brooks/Cole.}\keyword{methods}