The R Project SVN R

Rev

Rev 71909 | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
42333 ripley 1
% File src/library/methods/man/setClass.Rd
68948 ripley 2
% Part of the R package, https://www.R-project.org
71909 jmc 3
% Copyright 1995-2017 R Core Team
42333 ripley 4
% Distributed under GPL 2 or later
5
 
15357 jmc 6
\name{setClass}
56186 murdoch 7
\alias{setClass}
57843 jmc 8
\alias{classGeneratorFunction-class}
15357 jmc 9
\title{Create a Class Definition}
10
\description{
71366 jmc 11
  Create  a class definition and return a generator function to create
71909 jmc 12
  objects from the class.  Typical usage will be
13
  of the style:
71366 jmc 14
 
71909 jmc 15
   \code{myClass <- setClass("myClass", slots= ...., contains =....)}
71366 jmc 16
 
71909 jmc 17
 where the first argument is the name of the new class and, if supplied, the arguments    
71366 jmc 18
  \code{slots=} and \code{contains=} specify the slots
19
  in the new class and existing classes from which the new class
20
  should inherit.  Calls to \code{setClass()} are normally found in the
21
  source of a package; when the package is loaded the class will be
71909 jmc 22
  defined in the package's namespace.  Assigning the generator
23
  function with the name of the class is  convenient for users, but
24
  not a requirement.
19029 hornik 25
}
15357 jmc 26
\usage{
23531 hornik 27
setClass(Class, representation, prototype, contains=character(),
48694 jmc 28
         validity, access, where, version, sealed, package,
61478 jmc 29
         S3methods = FALSE, slots)
15357 jmc 30
}
31
\arguments{
45824 jmc 32
  \item{Class}{character string name for the class.}
71909 jmc 33
  \item{slots}{  The names and classes for the slots in the new class.  This argument
71366 jmc 34
      must be supplied by name, \code{slots=}, in the call, for back compatibility
35
      with other arguments no longer recommended.
45824 jmc 36
 
71909 jmc 37
      The argument must be  vector with a names attribute, the names being those of the slots in
38
      the new class.  Each element of the vector specifies an
39
      existing class; the corresponding slot must be from this class
40
      or a subclass of it.  Usually, this is a character vector
41
      naming the classes.  It's also legal for the elements of the
42
      vector to be class representation objects, as returned by \code{\link{getClass}}.
61478 jmc 43
 
71909 jmc 44
 
45
    As a limiting
46
    case,  the argument may be an unnamed character
47
    vector;  the elements are  taken as slot names and all slots have
48
    the unrestricted class \code{"ANY"}. 
70613 maechler 49
  }
71366 jmc 50
  \item{contains}{ A vector specifying existing classes from which
51
      this class should inherit. The new class will have all the slots
52
      of the superclasses, with the same requirements on the classes
53
      of these slots.  This argument
54
      must be supplied by name, \code{contains=}, in the call, for back compatibility
55
      with other arguments no longer recommended.
56
 
57
      See the section \sQuote{Virtual Classes} for the special
58
      superclass  \code{"VIRTUAL"}.
59
 
60
    }
61
  \item{prototype, where, validity, sealed, package}{
62
      \emph{These arguments are currently allowed, but either they are unlikely to be
63
        useful or there are modern alternatives that are preferred.}
64
 
65
     \code{prototype}: supplies an object with the default
66
    data for the slots in this class.  A more flexible approach is to
67
    write a method for \code{\link{initialize}()}.
68
 
69
  \code{where}: supplies an environment in which to store the definition.
70
    Should not be used:  For calls to
71
    \code{setClass()} appearing in the source code for a package the
72
    definition will be stored in the namespace of the package.
73
 
74
  \code{validity}: supplied a validity-checking method
75
    for objects from this class.  For clearer code, use a separate
76
    call to \code{\link{setValidity}()}.
77
 
78
  \code{sealed}: if \code{TRUE}, the class definition will be sealed,
79
    so that another call to \code{setClass} will fail on this class
80
    name.  But the definition is automatically sealed after the
81
    namespace is loaded, so explicit sealing it is not needed.
82
 
83
  \code{package}: supplies an optional package name for the class, but
84
  the class attribute should be  the package in which the class
85
  definition is assigned, as it is by default.
29714 ripley 86
  }
71366 jmc 87
 
88
  \item{representation, access, version, S3methods }{\emph{All these
70613 maechler 89
    arguments are deprecated from version 3.0.0 of \R and should be
71366 jmc 90
    avoided}.
61478 jmc 91
 
70613 maechler 92
    \code{representation} is an argument inherited from S that
93
    included both \code{slots} and \code{contains}, but the use of
94
    the latter two arguments is clearer and recommended.
95
 
96
    \code{access} and \code{version} are included for
97
    historical compatibility with S-Plus, but ignored.
71366 jmc 98
 
99
    \code{S3methods} is a flag indicating that old-style methods
100
    will be written involving this class; ignored now.
70613 maechler 101
  }
29714 ripley 102
}
57843 jmc 103
 
104
\value{
105
  A generator function suitable for creating objects from the class is
106
  returned, invisibly.  A call to this function generates a call to
107
  \code{\link{new}} for the class.  The call takes any number of arguments,
108
  which will be passed on to the initialize method.  If no
109
  \code{initialize} method is defined for the class or one of its
110
  superclasses, the default method expects named arguments with the
71909 jmc 111
  name of one of the slots and unnamed arguments that are objects from
112
  one of the contained classes.
57843 jmc 113
 
114
  Typically the generator function is assigned the name of the class,
115
  for programming clarity.  This is not a requirement and objects
116
  from the class can also be generated directly from
117
  \code{\link{new}}.  The advantages of the generator function are a
118
  slightly simpler and clearer call, and that the call will contain
119
  the package name of the class (eliminating any ambiguity if two
120
  classes from different packages have the same name).
121
 
122
  If the class is virtual, an attempt to generate an object  from
123
  either the generator or \code{new()}
124
  will result in an error.
125
}
45824 jmc 126
\section{Basic Use: Slots and Inheritance}{
57843 jmc 127
The two essential arguments other than the class name are
61478 jmc 128
\code{slots} and \code{contains}, defining the explicit slots
45824 jmc 129
and the inheritance (superclasses). Together, these arguments define
130
all the information in an object from this class; that is, the names
131
of all the slots and the classes required for each of them.
25351 jmc 132
 
45824 jmc 133
The name of the class determines
51867 maechler 134
which methods apply directly to objects from this class.  The
71366 jmc 135
superclass information specifies which methods apply indirectly,
136
through inheritance.  See \link{Methods_Details} for inheritance in method
137
selection.
29714 ripley 138
 
71366 jmc 139
 
45824 jmc 140
The slots in a class definition will be the union of all the slots
61478 jmc 141
specified directly by \code{slots} and all the slots in all
45824 jmc 142
the contained classes.
71909 jmc 143
There can only be one slot with a given name.
144
A class may override the definition of a slot with a given name, but
145
\emph{only} if the newly specified class is a subclass of the
146
inherited one.
147
For example, if the contained class had a slot \code{a} with class
148
\code{"ANY"}, then a subclass could specify \code{a} with class
149
\code{"numeric"},
150
but if the original specification for the slot was class
151
\code{"character"}, the new call to \code{setClass} would generate an error.
25351 jmc 152
 
17000 jmc 153
 
45824 jmc 154
 
61478 jmc 155
  Slot names \code{"class"} and \code{"Class"} are not allowed.
51867 maechler 156
  There are other slot names with a special meaning; these names start with
47936 jmc 157
  the \code{"."} character.  To be safe, you should define all of
47935 jmc 158
  your own slots with names starting with an alphabetic character.
71366 jmc 159
 
160
Some inherited classes will be treated specially---object types, S3
161
classes and a few special cases---whether inherited
162
directly or indirectly.  See the next three sections.
15357 jmc 163
}
164
 
71366 jmc 165
\section{Virtual Classes}{
57843 jmc 166
 
71366 jmc 167
      Classes exist for which no actual objects can be created, the
168
      \emph{virtual} classes.
57843 jmc 169
 
71366 jmc 170
 
171
      The most common and useful form of virtual class is the \emph{class
172
        union}, a virtual class that is defined in a call to
173
      \code{\link{setClassUnion}()} rather than a call to
174
      \code{setClass()}.
175
      This call lists the \emph{members} of the union---subclasses
176
      that extend the new class.
177
      Methods that are written with the class union in the signature
178
      are eligible for use with objects from any of the member classes.
179
      Class
180
      unions can include as members classes whose
181
      definition is otherwise sealed, including basic \R data types.
182
 
183
      Calls to \code{setClass()} will also create a virtual class,
184
      either when only the \code{Class} argument is supplied (no slots
185
      or superclasses) or when the \code{contains=} argument includes
186
      the special class name \code{"VIRTUAL"}.
187
 
188
      In the latter case, a
189
      virtual class may include
190
      slots to provide some common behavior without fully defining
191
      the object---see the class \code{\linkS4class{traceable}} for an
192
      example.
193
      Note that  \code{"VIRTUAL"} does not carry over to subclasses; a
194
      class that contains a virtual class is not itself automatically virtual.
195
 
196
}
197
 
47935 jmc 198
\section{Inheriting from Object Types}{
199
In addition to containing other S4 classes, a class definition can
47936 jmc 200
contain either an S3 class (see the next section) or a built-in R pseudo-class---one
47935 jmc 201
of the \R
202
object types or one of the special \R pseudo-classes \code{"matrix"} and
48946 murdoch 203
\code{"array"}.
47935 jmc 204
A class can contain at most one of the object types, directly or indirectly.
205
When it does, that contained class determines the \dQuote{data part}
206
of the class.
71366 jmc 207
This appears as a pseudo-slot, \code{".Data"} and can be treated as a
208
slot but actually determines
209
the type of objects from this slot.
15357 jmc 210
 
47935 jmc 211
Objects from the new class try to inherit the built in
212
behavior of the contained type.
213
In the case of normal \R data types, including vectors, functions and
214
expressions, the implementation is relatively straightforward.
215
For any object \code{x} from the class,
216
\code{typeof(x)} will be the contained basic type; and a special
217
pseudo-slot, \code{.Data}, will be shown with the corresponding class.
218
See the \code{"numWithId"} example below.
15357 jmc 219
 
57843 jmc 220
Classes may also inherit from \code{"vector"}, \code{"matrix"} or
221
\code{"array"}.
222
The data part of these objects can be any vector data type.
223
 
224
For an object from any class that does \emph{not} contain one of these
225
types or classes,
47935 jmc 226
\code{typeof(x)} will be \code{"S4"}.
15357 jmc 227
 
47935 jmc 228
Some \R data types do not behave normally, in the sense that they are
229
non-local references or other objects that are not duplicated.
230
Examples include those corresponding to classes \code{"environment"}, \code{"externalptr"}, and \code{"name"}.
231
These can not be the types for objects with user-defined
232
classes (either S4 or S3) because setting an attribute overwrites the
233
object in all contexts.
234
It is possible to define a class that inherits from such types,
235
through an indirect mechanism that stores the inherited object in a
71909 jmc 236
reserved slot, \code{".xData"}.
57843 jmc 237
See the
47936 jmc 238
example for class \code{"stampedEnv"} below.
71909 jmc 239
An object from such a class does \emph{not} have a \code{".Data"} pseudo-slot.
240
 
241
For most computations, these classes behave transparently as if they
242
inherited directly from the anomalous type.
57843 jmc 243
S3 method dispatch and the relevant \code{as.}\emph{type}\code{()}
244
functions should behave correctly, but code that uses the type of the
245
object directly will not.
71909 jmc 246
For example, \code{as.environment(e1)} would work as expected with the
247
\code{"stampedEnv"} class, but \code{typeof(e1)} is \code{"S4"}.
47935 jmc 248
 
31085 jmc 249
}
29714 ripley 250
 
47935 jmc 251
\section{Inheriting from S3 Classes}{
252
Old-style S3 classes have no formal definition.  Objects are
253
\dQuote{from} the class when their class attribute contains the
254
character string considered to be the class name.
31085 jmc 255
 
47935 jmc 256
Using such classes with formal classes and methods is necessarily a
257
risky business, since there are no guarantees about the content of the
258
objects or about consistency of inherited methods.
259
Given that, it is still possible to define a class that inherits from
260
an S3 class, providing that class has been registered as an old class
261
(see \code{\link{setOldClass}}).
262
 
57843 jmc 263
Broadly speaking, both S3 and S4 method dispatch try to behave
264
sensibly with respect to inheritance in either system.
265
Given an S4 object, S3 method dispatch and the \code{\link{inherits}}
266
function should use the S4 inheritance information.
267
Given an S3 object, an S4 generic function will dispatch S4 methods
268
using the S3 inheritance, provided that inheritance has been declared via
71366 jmc 269
\code{\link{setOldClass}}.  For details, see \code{\link{setOldClass}}
270
and Section 10.8 of the reference.
57843 jmc 271
 
47935 jmc 272
}
273
 
45824 jmc 274
\section{Classes and Packages}{
31085 jmc 275
 
45824 jmc 276
Class definitions normally belong to packages (but can be defined in
277
the  global environment as well, by evaluating the expression on the
278
command line or in a file sourced from the command line).
279
The corresponding package name is part of the class definition; that
71366 jmc 280
is, part of the \code{\linkS4class{classRepresentation}} object holding that
45824 jmc 281
definition.  Thus, two classes with the same name can exist in
282
different packages, for most purposes.
31085 jmc 283
 
57843 jmc 284
When a class name is supplied for a slot or a superclass in a call to
285
\code{setClass}, a
45824 jmc 286
corresponding class definition will be found, looking from the
57843 jmc 287
namespace of the current package, assuming the call in question appears directly in the source for the
288
package, as it should to avoid ambiguity.
289
The  class definition
71366 jmc 290
must be already defined in this package, in the imports directives of
291
the package's \code{DESCRIPTION} and
292
\code{NAMESPACE} files or in the basic classes defined by the methods package.
293
(The \sQuote{methods} package must be included in the imports directives
294
for any package that uses
295
S4 methods and classes, to satisfy the
296
\code{"CMD check"} utility.)
31085 jmc 297
 
71366 jmc 298
If a package imports two classes of the same name from separate packages, the \code{\link{packageSlot}}
299
of the \code{name} argument needs to be set to the package name of the
300
particular class.
45824 jmc 301
This should be a rare occurrence.
37810 ripley 302
}
303
 
15357 jmc 304
\references{
88585 hornik 305
  \bibshow{R:Chambers:2016}
306
  (Chapters 9 and 10.)
71366 jmc 307
}
15357 jmc 308
 
33556 maechler 309
\seealso{
71366 jmc 310
  \code{\link{Classes_Details}} for a general discussion of classes,
311
  \code{\link{Methods_Details}} for an analogous discussion of methods,
33556 maechler 312
  \code{\link{makeClassRepresentation}}
313
}
15357 jmc 314
\examples{
26000 ripley 315
\dontshow{
33353 maechler 316
 if(isClass("trackMultiCurve")) removeClass("trackMultiCurve")
47616 ripley 317
 if(isClass("trackCurve"))      removeClass("trackCurve")
318
 if(isClass("track"))           removeClass("track")
15357 jmc 319
}
320
## A simple class with two slots
70613 maechler 321
track <- setClass("track", slots = c(x="numeric", y="numeric"))
57843 jmc 322
## an object from the class
323
t1 <- track(x = 1:10, y = 1:10 + rnorm(10))
324
 
15357 jmc 325
## A class extending the previous, adding one more slot
57838 jmc 326
trackCurve <- setClass("trackCurve",
70613 maechler 327
		slots = c(smooth = "numeric"),
328
		contains = "track")
57843 jmc 329
 
330
## an object containing a superclass object
331
t1s <- trackCurve(t1, smooth = 1:10)
332
 
15357 jmc 333
## A class similar to "trackCurve", but with different structure
334
## allowing matrices for the "y" and "smooth" slots
23531 hornik 335
setClass("trackMultiCurve",
61478 jmc 336
         slots = c(x="numeric", y="matrix", smooth="matrix"),
23531 hornik 337
         prototype = list(x=numeric(), y=matrix(0,0,0),
338
                          smooth= matrix(0,0,0)))
17376 jmc 339
 
31085 jmc 340
## A class that extends the built-in data type "numeric"
341
 
61478 jmc 342
numWithId <- setClass("numWithId", slots = c(id = "character"),
33353 maechler 343
         contains = "numeric")
31085 jmc 344
 
57838 jmc 345
numWithId(1:3, id = "An Example")
31085 jmc 346
 
47936 jmc 347
## inherit from reference object of type "environment"
70613 maechler 348
stampedEnv <- setClass("stampedEnv", contains = "environment",
349
                       slots = c(update = "POSIXct"))
47936 jmc 350
setMethod("[[<-", c("stampedEnv", "character", "missing"),
351
   function(x, i, j, ..., value) {
352
       ev <- as(x, "environment")
353
       ev[[i]] <- value  #update the object in the environment
354
       x@update <- Sys.time() # and the update time
355
       x})
356
 
57838 jmc 357
 
358
e1 <- stampedEnv(update = Sys.time())
359
 
47936 jmc 360
e1[["noise"]] <- rnorm(10)
361
 
26000 ripley 362
\dontshow{
15357 jmc 363
tMC <- new("trackMultiCurve")
364
is.matrix(slot(tMC, "y"))
365
is.matrix(slot(tMC, "smooth"))
366
setClass("myMatrix", "matrix", prototype = matrix(0,0,0))
367
nrow(new("myMatrix")) # 0
368
nrow(new("matrix")) # 1
17007 jmc 369
## simple test of prototype data
41508 ripley 370
xxx <- stats::rnorm(3)
61478 jmc 371
setClass("xNum", slots = c(x = "numeric"), prototype = list(x = xxx))
17007 jmc 372
stopifnot(identical(new("xNum")@x, xxx))
21853 jmc 373
 
57838 jmc 374
removeClass("xNum")
375
removeClass("myMatrix")
21853 jmc 376
 
18126 jmc 377
## The following should not be needed.  But make check removes all files
378
## between example files, in a crude way that does not cause the class
379
## information to be reset.  There seems no way to detect this, so we
380
## have to remove classes ourselves
381
 
23531 hornik 382
removeClass("trackMultiCurve")
383
removeClass("trackCurve")
384
removeClass("track")
33556 maechler 385
}%dont show
15357 jmc 386
}
387
\keyword{programming}
388
\keyword{classes}
389
\keyword{methods}