Skip to content
Tutorials Center
My learning

Topics

Lesson 26 of 38 ยท CLOS Object System

CLOS: Classes, Slots and Instances

Meet the Common Lisp Object System: define classes with defclass, configure slots with initargs, readers, writers and defaults, create instances and inspect them.

The Common Lisp Object System (CLOS) is one of the most flexible object systems in any language. It differs from the class-based systems of Java or Python in one fundamental way: methods do not belong to classes. Classes hold data (slots); behavior is defined separately by generic functions (next lesson). This lesson covers the data half.

No Common Lisp implementation runs on this site, so the CLOS code is read-only and I only show output I am certain about. The JavaScript examples are labelled stand-ins that model the same ideas with JS classes and objects.

defclass

LISP
(defclass person ()
  ((name :initarg :name
         :accessor person-name)
   (age  :initarg :age
         :initform 0
         :reader person-age)))

The first list after the class name is the list of superclasses (empty here; standard-object is implied). Then comes the list of slot specifications. A slot spec is a name followed by options:

Option Meaning
:initarg :name keyword accepted by make-instance to set the slot
:initform expr default value expression, evaluated each time an instance is made if no initarg is given
:accessor f defines f (reader) and (setf f) (writer)
:reader f defines only the reader
:writer f defines only a writer (setf f)
:type type declared type (implementations may or may not check it)
:documentation "โ€ฆ" docstring
:allocation :class one shared slot for all instances (default :instance)

Making instances

LISP
(defvar *ada* (make-instance 'person :name "Ada" :age 36))

(person-name *ada*)        ; => "Ada"
(person-age *ada*)         ; => 36
(setf (person-name *ada*) "Ada Lovelace")
(person-name *ada*)        ; => "Ada Lovelace"
(person-age (make-instance 'person :name "Bob"))   ; => 0  (the :initform)

make-instance takes the class (usually a quoted symbol) and keyword arguments for the slots. A slot with neither :initarg supplied nor :initform is unbound; reading it signals an error, whereas a slot with :initform nil is simply nil.

Two lower-level accessors are always available:

LISP
(slot-value *ada* 'name)            ; => "Ada Lovelace"
(setf (slot-value *ada* 'age) 37)
(slot-boundp *ada* 'name)           ; => T

slot-value ignores readers and writers, so use accessors in application code and keep slot-value for generic tools such as serializers and the debugger.

JS Stand-in: slots, initargs and defaults

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Initforms are evaluated per instance

An :initform is an expression, not a value, and it is evaluated at each instance creation, in the lexical environment of the defclass. That makes it safe to put mutable objects in a default:

LISP
(defclass shopping-cart ()
  ((items :initform (list) :accessor cart-items)
   (created :initform (get-universal-time) :reader cart-created)))

Each cart gets its own fresh list, and its own creation time. Contrast with a Python default argument, which is shared.

Class slots (shared)

:allocation :class stores one value for all instances:

LISP
(defclass counter-widget ()
  ((count :allocation :class :initform 0 :accessor widget-count)))

(let ((a (make-instance 'counter-widget))
      (b (make-instance 'counter-widget)))
  (incf (widget-count a))
  (widget-count b))       ; => 1

Use sparingly: shared slots behave like global variables and complicate redefinition.

Printing and describing

The default printed form is not informative (#<PERSON {1003A5B2C3}> in SBCL). Two tools help:

LISP
(describe *ada*)       ; prints the class and each slot with its value
(class-of *ada*)       ; => #<STANDARD-CLASS COMMON-LISP-USER::PERSON>
(type-of *ada*)        ; => PERSON
(typep *ada* 'person)  ; => T

The exact output format of describe differs between implementations. To control printing, define a method on print-object (the slots and MOP lesson shows how).

Redefining a class on the fly

Because Common Lisp is interactive, you may re-evaluate a defclass in a running image. Existing instances are updated lazily the next time they are accessed, and you can customize that with update-instance-for-redefined-class. This is a major reason Lisp programs can be modified without restarting. Removing a slot discards its value; adding a slot gives it its :initform or leaves it unbound.

Structures versus classes

defstruct is the lighter alternative: it gives you a constructor, accessors and a copier with faster slot access, but no multiple inheritance, limited redefinition support and (in the usual style) no dispatch-friendly flexibility. A rule of thumb: use defstruct for simple records in performance-sensitive code and defclass when you need generic functions, multiple inheritance, or interactive redefinition. Both work with generic functions, since a structure also defines a type.

LISP
(defstruct point (x 0) (y 0))
(let ((p (make-point :x 3)))
  (list (point-x p) (point-y p)))   ; => (3 0)

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. In CLOS, where do methods live?

    Classes hold slots; behavior is attached to generic functions that dispatch on argument classes.
  2. 2. What does :initarg :name do?

    An initarg is the keyword used with make-instance. The default value is the :initform.
  3. 3. When is an :initform expression evaluated?

    That is why (list) or (make-hash-table) as an initform gives each instance its own object.
  4. 4. What happens when you read a slot that has no initarg value and no initform?

    Unbound is a distinct state from NIL; use slot-boundp to test it.

Summary

  • defclass declares slots; options give initargs, defaults, accessors, types and sharing.
  • make-instance creates instances; :initform is evaluated per instance.
  • Use accessors in normal code; slot-value is the low-level escape hatch.
  • Classes can be redefined in a live image and instances update lazily.
  • defstruct is a lighter alternative for simple records.

Next: Generic Functions and Methods