【问题标题】:Checking parent class of an object检查对象的父类
【发布时间】:2014-07-18 11:13:52
【问题描述】:

我想知道一种方法如何检查一个对象是否属于某个类,或者是从它派生的。例如:

(defclass a nil
  nil)

(defclass b (a)
  nil)

(defparameter *foo* (make-instance 'b))

(my-function *foo* 'a) ; => t
(my-function *foo* 'b) ; => t

或者,也可以使用返回给定对象(或类)的所有基类列表的函数。

【问题讨论】:

标签: inheritance lisp common-lisp clos


【解决方案1】:

使用typep:

CL-USER 4 > (typep *foo* 'a)
T

CL-USER 5 > (typep *foo* 'b)
T

【讨论】:

    【解决方案2】:

    您需要使用 MOP(元对象协议)`class-direct-superclasses'

    快速加载库 close-mop 并像这样使用 `class-direct-superclasses':

    CL-USER> (closer-mop:class-direct-superclasses (find-class 'number))
    (#<BUILT-IN-CLASS T>)
    CL-USER>
    

    如果你有一个类的实例,你可以这样做

    CL-USER> (let ((table (make-instance 'test-table-2)))
               (class-direct-superclasses (class-of table)))
    (#<STANDARD-CLASS STANDARD-OBJECT>)} 
    CL-USER>
    

    一个可能的问题(在库中记录):如果你 DEFPACKGE :USE close-mop,而不是使用 CL,:USE close-common-lisp

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-07-07
      • 2018-10-08
      • 2018-02-21
      • 1970-01-01
      • 1970-01-01
      • 2017-05-25
      • 1970-01-01
      • 2011-07-17
      相关资源
      最近更新 更多