11.4 基类 (Superclasses)
defclass
接受的第二个参数是一个列出其基类的列表。一个类别继承了所有基类槽的联集。所以要是我们将 screen-circle
定义成 circle
与 graphic
的子类,
(defclass graphic ()
((color :accessor graphic-color :initarg :color)
(visible :accessor graphic-visible :initarg :visible
:initform t)))
(defclass screen-circle (circle graphic) ())
则 screen-circle
的实例会有四个槽,分别从两个基类继承而来。一个类别不需要自己创建任何新槽; screen-circle
的存在,只是为了提供一个可创建同时从 circle
及 graphic
继承的实例。
访问器及 :initargs
参数可以用在 screen-circle
的实例,就如同它们也可以用在 circle
或 graphic
类别那般:
> (graphic-color (make-instance 'screen-circle
:color 'red :radius 3))
RED
我们可以使每一个 screen-circle
有某种缺省的颜色,通过在 defclass
里替这个槽指定一个 :initform
:
(defclass screen-circle (circle graphic)
((color :initform 'purple)))
现在 screen-circle
的实例缺省会是紫色的:
> (graphic-color (make-instance 'screen-circle))
PURPLE
当前内容版权归 readthedocs 或其关联方所有,如需对内容或内容相关联开源项目进行关注与资助,请访问 readthedocs .