Rev 35751 | Blame | Compare with Previous | Last modification | View Log | Download | RSS feed
\name{Methods}\alias{Methods}\title{General Information on Methods}\description{This documentation section covers some general topics on how methodswork and how the \pkg{methods} package interacts with the rest of R. Theinformation is usually not needed to get started with methods andclasses, but may be helpful for moderately ambitious projects, or whensomething doesn't work as expected.The section \bold{How Methods Work} describes the underlyingmechanism; \bold{Class Inheritance and Method Selection} provides moredetails on how class definitions determine which methods are used.The section \bold{Changes with the Methods Package} outlines possibleeffects on other computations when running with package \pkg{methods}.}\section{How Methods Work}{A generic function is a function that has associated with it acollection of other functions (the methods), all of which agree informal arguments with the generic. In R, the \dQuote{collection} is anobject of class \code{"\link{MethodsList}"}, which contains a namedlist of methods (the \code{methods} slot), and the name of one of theformal arguments to the function (the \code{argument} slot). Thenames of the methods are the names of classes, and the correspondingelement defines the method or methods to be used if the correspondingargument has that class. For example, suppose a function \code{f} hasformal arguments \code{x} and \code{y}. The methods list object forthat function has the object \code{as.name("x")} as its\code{argument} slot. An element of the methods named \code{"track"}is selected if the actual argument corresponding to \code{x} is anobject of class \code{"track"}. If there is such an element, it cangenerally be either a function or another methods list object.In the first case, the function defines the method to use for any callin which \code{x} is of class \code{"track"}. In the second case, thenew methods list object defines the selection of methods depending onthe remaining formal arguments, in this example, \code{y}. The sameselection process takes place, recursively, using the new methods list.Eventually, the selection returns either a function or \code{NULL},meaning that no method matched the actual arguments.Each method selected corresponds conceptually to a \emph{signature};that is a named list of classes, with names corresponding to some orall of the formal arguments. In the previous example, if selectingclass \code{"track"} for \code{x}, finding that the selection wasanother methods list and then selecting class \code{"numeric"} for\code{y} would produce a method associated with the signature\code{x = "track", y = "numeric"}.The actual selection is done recursively, but you can see the methodsarranged by signature by calling the function\code{\link{showMethods}}, and objects with the methods arranged thisway (in two different forms) are returned by the functions\code{\link{listFromMlist}} and \code{\link{linearizeMlist}}.In an R session, each generic function has a single methods listobject defining all the currently available methods. The sessionmethods list object is created the first time the function is calledby merging all the relevant method definitions currently visible.Whenever something happens that might change the definitions (such asattaching or detaching a package with methods for this function, orexplicitly defining or removing methods), the merged methods listobject is removed. The next call to the function will recompute themerged definitions.When methods list are merged, they can come from two sources:\enumerate{\item Methods list objects for the same function anywhere on thecurrent search list. These are merged so that methods in anenvironment earlier in the search list override methods for the samefunction later in the search list. A method overrides onlyanother method for the same signature. See the comments on class\code{"ANY"} in the section on \bold{Inheritance}.\item Methods list objects corresponding the group genericfunctions, if any, for this function. Any generic function can bedefined to belong to a group generic. The methods for the groupgeneric are available as methods for this function. The groupgeneric can itself be defined as belong to a group; as a resultthere is a list of group generic functions. A method defined for afunction and a particular signature overrides a method for the samesignature for that function's group generic.}Merging is done first on all methods for a particular function, andthen over the generic and its group generics.The result is a single methods list object that contains all themethods \emph{directly} defined for this function. As calls to thefunction occur, this information may be supplemented by\emph{inherited} methods, which we consider next.}\section{Class Inheritance and Method Selection}{If no method is found directly for the actual arguments in a call to ageneric function, an attempt is made to match the available methods tothe arguments by using \emph{inheritance}.Each class definition potentially includes the names of one or moreclasses that the new class contains. (These are sometimes called the\emph{superclasses} of the new class.) These classes themselves mayextend other classes. Putting all this information together producesthe full list of superclasses for this class. (You can see this listfor any class \code{"A"} from the expression \code{extends("A")}.)In addition, any class implicitly extends class \code{"ANY"}.When all the superclasses are needed, as they are for dispatchingmethods, they are ordered by how direct they are: first, the directclasses contained directly in the definition of this class, then thesuperclasses of these classes, etc.The S language has an additional, explicit mechanism for defining superclasses, the\code{\link{setIs}} mechanism.This mechanism allows a class to extend another even though they donot have the same representation. The extension is made possible bydefining explicit methods to \code{coerce} an object to its superclassand to \code{replace} the data in the object corresponding to thesuperclass. The \code{\link{setIs}} mechanism will be used less oftenand only when directly including the superclass does not make sense,but once defined, the superclass acts just as directly containedclasses as far as method selection is concerned.A method will be selected by inheritance if we can find a method inthe methods list for a signature corresponding to anycombination of superclasses for each of the relevant arguments.The search for such a method is performed by the function\code{\link{MethodsListSelect}}, working as follows.The generic, \code{f} say, has a signature, which by defaultis all its formal arguments, except \dots (see\code{\link{setGeneric}}). For each of the formal arguments in thatsignature, in order, the class of the actual argument is matchedagainst available methods. A missing argument corresponds to class\code{"missing"}. If no method corresponds to the class of theargument, the evaluator looks for a method corresponding to thethe superclasses (the other classes that the actual classextends, always including\code{"ANY"}). If no match is found, the dispatch fails, with anerror. (But if there is a default method, that will always match.)If the match succeeds, it can find either a single method, or amethods list. In the first case, the search is over, and returnsthe method. In the second case, the search proceeds, with thenext argument in the signature of the generic. \emph{That} searchmay succeed or fail. If it fails, the dispatch will try again withthe next best match for the current argument, if there is one.The last match always corresponds to class \code{"ANY"}.The effect of this definition of the selection process is to order allpossible inherited methods, first by the superclasses for the firstargument, then within this by the superclasses for the secondargument, and so on.}\section{Changes with the Methods Package}{The \pkg{methods} package is designed to leave other computations in Runchanged. There are, however, a few areas where the defaultfunctions and behavior are overridden when running with the methodspackage attached. This section outlines those known to have somepossible effect.\describe{\item{\code{class}:}{The \pkg{methods} package enforces the notion that every objecthas a class; in particular, \code{class(x)} is never \code{NULL},as it would be for basic vectors, for example, when not using\pkg{methods}.In addition, when assigning a class, the value is required to be asingle string. (However, objects can have multiple class names ifthese were generated by old-style class computations. The methodspackage does not hide the \dQuote{extra} class names.)Computations using the notion of \code{NULL} class attributes orof class attributes with multiple class names are not reallycompatible with the ideas in the \pkg{methods} package. Formalclasses and class inheritance are designed to give more flexibleand reliable implementations of similar ideas.If you do have to mix the two approaches, any operations that useclass attributes in the old sense should be written in terms of\code{attr(x, "class")}, not \code{class(x)}. In particular, testfor no class having been assigned with\code{is.null(attr(x, "class"))}.}\item{Printing:}{To provide appropriate printing automatically for objects withformal class definitions, the \pkg{methods} package overrides\code{print.default}, to look for methods for the generic function\code{show}, and to use a default method for objects with formalclass definitions.The revised version of \code{print.default} is intended to produceidentical printing to the original version for any object thatdoes \emph{not} have a formally defined class, including honoringold-style print methods. So far, no exceptions are known.}}}\references{The R package \pkg{methods} implements, with a few exceptions, theprogramming interface for classesand methods in the book \emph{Programming with Data} (JohnM. Chambers, Springer, 1998), in particular sections 1.6, 2.7, 2.8,and chapters 7 and 8.While the programming interface for the \pkg{methods} package followsthe reference, the R software is an original implementation, sodetails in the reference that reflect the S4 implementation may appeardifferently in R. Also, there are extensions to the programminginterface developed more recently than the reference. For adiscussion of details and ongoing development, see the web page\url{http://developer.r-project.org/methodsPackage.html} and thepointers from that page.}\seealso{\code{\link{setGeneric}},\code{\link{setClass}}}\keyword{programming}\keyword{classes}\keyword{methods}