4

我想在类对象上定义方法,这些方法基于类的祖先继承,就像实例的方法继承一样。有没有办法做到这一点?

这是不起作用的:eql-方法专业化。考虑这个例子:

(defclass animal ()())
(defclass bird (animal)())
(defclass woodpecker (bird)())

(defmethod wings-p ((animal-class (eql (find-class 'animal)))) nil)
(defmethod wings-p ((bird-class   (eql (find-class 'bird))))   t)

调用会(wings-p (find-class 'woodpecker))生成一个no-method-error,您可以看到为什么 - classwoodpecker显然不是eql任何方法专家。

我想在 on 上定义“方法” birdanimal以便当我调用wings-pon时(find-class woodpecker)wings-p返回t

我觉得这是几乎所有其他 OO 系统的标准功能,但我不记得如何使用 CLOS 来做到这一点。

4

1 回答 1

5

(find-class 'bird)在and返回的对象之间确实没有直接的继承链接 (find-class 'woodpecker),正如你不能期望一个只专门化的泛型函数(eql 1)(eql 2)在给定值 3 时产生结果。

在您的情况下,您可以从STANDARD-CLASS. 您也需要定义方法VALIDATE-SUPERCLASS,然后您可以定义自己的具有适当:metaclass参数的类。例如(find-class 'animal)会返回一个animal-class. 然后,(eql (find-class 'animal))您将专注于animal-class. 更确切地说:

(defpackage :meta-zoo (:use :closer-common-lisp))
(in-package :meta-zoo)

(defclass animal-class (standard-class) ())
(defclass bird-class (animal-class) ())
(defclass woodpecker-class (bird-class) ())

(defmethod validate-superclass ((class animal-class)
                                (super standard-class)) t)

(defclass animal () () (:metaclass animal-class))
(defclass bird () () (:metaclass bird-class))
(defclass woodpecker () () (:metaclass woodpecker-class))

(defgeneric class-wing-p (class)
  (:method ((a animal-class)) nil)
  (:method ((b bird-class)) t))

(defparameter *woody* (make-instance 'woodpecker))

(class-of *woody*)
;; => #<woodpecker-class woodpecker>

(class-wing-p (class-of *woody*))
;; => t
于 2016-02-17T17:05:00.740 回答