You can make an instance of a class with MAKE-INSTANCE
. It's
similar to the MAKE-x
functions defined by DEFSTRUCT
but lets you
pass the class to instantiate as an argument:
(MAKE-INSTANCE class {initarg value}*)
Instead of the class object itself, you can use its name. For example:
(make-instance 'person :age 100)
This person object would have age 100
and name BILL
, the default.
It's often a good idea to define your own constructor functions,
rather than call MAKE-INSTANCE
directly, because you can hide
implementation details and don't have to use keyword parameters
for everything. For instance, you might want to define
(defun make-person (name age)
(make-instance 'person :name name :age age))
if you wanted the name and age to be required, positional parameters, rather than keyword parameters.
The accessor functions can be used to get and set slot values:
<cl> (setq p1 (make-instance 'person :name 'jill :age 100))
#<person @ #x7bf826>
<cl> (person-name p1)
jill
<cl> (person-age p1)
100
<cl> (setf (person-age p1) 101)
101
<cl> (person-age p1)
101
Note that when you use DEFCLASS
, the instances are printed using
the #<...>
notation, rather than
as #s(person :name jill :age 100)
.
But you can change the way instances are printed by defining methods
on the generic function PRINT-OBJECT
.
Slots can also be accessed by name using (SLOT-VALUE instance slot-name)
:
<cl> (slot-value p1 'name)
jill
<cl> (setf (slot-value p1 'name) 'jillian)
jillian
<cl> (person-name p1)
jillian
You can find out various things about an instance by calling
DESCRIBE
:
<cl> (describe p1)
#<person @ #x7bf826> is an instance
of class #<clos:standard-class person @ #x7ad8ae>:
The following slots have :INSTANCE allocation:
age 101
name jillian