common-lisp Creating a basic CLOS class without parents


Example

A CLOS class is described by:

  • a name
  • a list of superclasses
  • a list of slots
  • further options like documentation

Each slot has:

  • a name
  • an initialization form (optional)
  • an initialization argument (optional)
  • a type (optional)
  • a documentation string (optional)
  • accessor, reader and/or writer functions (optional)
  • further options like allocation

Example:

(defclass person ()
  ((name
    :initform      "Erika Mustermann" 
    :initarg       :name 
    :type          string
    :documentation "the name of a person"
    :accessor      person-name)
   (age
    :initform      25
    :initarg       :age
    :type          number
    :documentation "the age of a person"
    :accessor      person-age))
  (:documentation "a CLOS class for persons with name and age"))

A default print method:

(defmethod print-object ((p person) stream)
  "The default print-object method for a person"
  (print-unreadable-object (p stream :type t :identity t)
    (with-slots (name age) p
      (format stream "Name: ~a, age: ~a" name age))))

Creating instances:

CL-USER > (make-instance 'person)
#<PERSON Name: Erika Mustermann, age: 25 4020169AB3>

CL-USER > (make-instance 'person :name "Max Mustermann" :age 24)
#<PERSON Name: Max Mustermann, age: 24 4020169FEB>