You define a class with DEFCLASS
:
(DEFCLASS class-name (superclass-name*)
(slot-description*)
class-option*)
For simple things, forget about class options.
A slot-description has the form (slot-name slot-option*)
, where each
option is a keyword followed by a name, expression, or whatever. The
most useful slot options are
function-name
expression
symbol
(Initargs are usually keywords.)
DEFCLASS
is similar to DEFSTRUCT
. The syntax is a bit different, and
you have more control over what things are called. For instance,
consider the DEFSTRUCT
:
(defstruct person
(name 'bill)
(age 10))
DEFSTRUCT
would automatically define slots with expressions to
compute default initial values, access-functions like PERSON-NAME
to get and set slot values, and a MAKE-PERSON
that took keyword
initialization arguments (initargs)
as in
(make-person :name 'george :age 12)
A DEFCLASS
that provided similar access functions, etc, would be:
(defclass person ()
((name :accessor person-name
:initform 'bill
:initarg :name)
(age :accessor person-age
:initform 10
:initarg :age)))
Note that DEFCLASS
lets you control what things are called. For
instance, you don't have to call the accessor PERSON-NAME
. You could
call it NAME
.
In general, you should pick names that make sense for a group of
related classes rather than rigidly following the DEFSTRUCT
conventions.
You do not have to provide all options for every slot.
Maybe you don't want it to be possible to initialize a slot
when calling MAKE-INSTANCE
(for which see below). In that case,
don't provide an :INITARG
. Or maybe there isn't a meaningful
default value. (Perhaps the meaningful values will always be
specified by a subclass.) In that case, no :INITFORM
.
Note that classes are objects. To get the class object from its
name, use (FIND-CLASS name)
. Ordinarily, you won't need to do this.