创建没有父项的基本 CLOS 类

CLOS 类描述如下:

  • 一个名字
  • 超类列表
  • 插槽列表
  • 更多选项,如文档

每个插槽都有:

  • 一个名字
  • 初始化表单(可选)
  • 初始化参数(可选)
  • 一种类型(可选)
  • 文档字符串(可选)
  • 存取器,读取器和/或写入器功能(可选)
  • 其他选项如分配

例:

(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"))

默认打印方法:

(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))))

创建实例:

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>