【问题标题】:Is there a way to get the slots of a class?有没有办法获得班级的名额?
【发布时间】:2017-04-06 03:20:53
【问题描述】:

我有这样的课

(defclass shape ()
 ((color :initform :black)
 (thickness :initform 1)
 (filledp :initform nil)
 (window :initform nil)))

如果我只知道此类的实例,common-lisp 中是否有一个函数如何获取这些插槽的列表?

【问题讨论】:

  • 好的,谢谢你的回答。但我还有另一个问题。我需要知道课堂上的每一种方法。甚至来自继承类的方法。 (defclass point (shape) ((x :initform 0) (y :initform 0))) 有没有办法,如何获取?
  • 查看链接的问题。
  • 但是我不能使用任何外部库。

标签: class common-lisp slots clos lispworks


【解决方案1】:

许多 Common Lisp 实现都支持 CLOS 元对象协议。这为类、槽和其他元对象提供了内省操作。

在 LispWorks 中,相应的函数可以在包CL-USER 中直接访问。

CL-USER 139 > (defclass shape ()
                ((color :initform :black)
                 (thickness :initform 1)
                 (filledp :initform nil)
                 (window :initform nil)))
#<STANDARD-CLASS SHAPE 40202910E3>

CL-USER 140 > (mapcar #'slot-definition-name
                      (class-direct-slots (class-of (make-instance 'shape))))
(COLOR THICKNESS FILLEDP WINDOW)

slot-definition-nameclass-direct-slots 函数由 CLOS 的元对象协议定义,并在许多 Common Lisp 实现中得到支持——只是它们所在的包可能不同。例如,在 SBCL 中,可能会在包 SB-MOP 中找到它们。

我们可以从一个类中获得直接槽的列表。直接槽是为该类直接定义的并且不被继承的槽。如果要获取所有插槽的列表,请使用函数class-slots

Slot这里的意思是我们得到一个slot定义对象,它描述了slot。要获取插槽的名称,您必须使用函数slot-definition-name 从插槽定义对象中检索名称。

【讨论】:

  • @Micky 另见github.com/pcostanza/closer-mop。您还可以使用(apropos 'slot-definition-name) 找出在您的实现中定义了这些功能的包。
  • @coredump 谢谢,这帮助我弄清楚如何在 sbcl 上运行它:
  • (mapcar #'sb-mop:slot-definition-name (sb-mop:class-direct-slots (class-of (make-instance 'shape))))
猜你喜欢
  • 2012-10-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多