Classes and Instances

Redefining a class at the REPL updates existing instances (slots are added/removed). Customize the migration with update-instance-for-redefined-class. Change an instance's class with change-class.

(defclass person ()
  ((name :initarg :name                ; keyword used in make-instance
         :initform "Anonymous"         ; default value
         :accessor person-name         ; reader + (setf person-name) writer
         :type string
         :documentation "The person's name.")
   (age  :initarg :age
         :initform 0
         :reader person-age            ; read-only accessor
         :writer set-person-age)       ; separate writer function
   (id   :allocation :class            ; shared by all instances (class slot)
         :initform 0
         :accessor person-id-counter))
  (:documentation "A person with a name and an age."))

(defparameter *ana* (make-instance 'person :name "Ana" :age 30))
(person-name *ana*)                    ; "Ana"
(setf (person-name *ana*) "Ana B.")
(person-age *ana*)                     ; 30
(set-person-age 31 *ana*)
(slot-value *ana* 'name)               ; direct slot access
(slot-boundp *ana* 'name)              ; T
(with-accessors ((n person-name) (a person-age)) *ana*
  (format nil "~a is ~a" n a))
(with-slots (name age) *ana*           ; symbol-macros over slots
  (setf age 32)
  (list name age))
(class-of *ana*)                      
…