new to create an object from a
particular class can be interpreted specially for that class, by the
definition of a method for function initialize for the class.
This documentation describes some existing methods, and also outlines
how to write new ones. The arguments to initialize are .Object and
.... Nearly always, initialize is called from new,
not directly. The .Object argument is then the
prototype object from the class.
Two techniques are often appropriate for initialize methods:
special argument names and callNextMethod.
You may want argument names that are more natural to your users than
the (default) slot names. These will be the formal arguments to
your method definition, in addition to .Object (always) and
...(optionally). For example, the method for class
"traceable" documented above would be created by a call to
setMethod of the form:
setMethod("initialize", "traceable", function(.Object, def, tracer, exit, at, print) \dots )
In this example, no other arguments are meaningful, and the resulting method will throw an error if other names are supplied.
When your new class extends another class, you may want to call the
initialize method for this superclass (either a special method or the
default). For example, suppose you want to define a method for your
class, with special argument x, but you also want users to be
able to set slots specifically. If you want x to override the
slot information, the beginning of your method definition might look
something like this:
function(.Object, x, ...) { Object <- callNextMethod(.Object, ...) if(!missing(x)) { # do something with x
You could also choose to have the inherited method override, by first
interpreting x, and then calling the next method.