有没有办法获得一个班级的空缺? [英] Is there a way to get the slots of a class?

查看:121
本文介绍了有没有办法获得一个班级的空缺?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个像这样的班

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

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

Is there a function in common-lisp how to get a list of those slots if i only know instance of this class?

推荐答案

许多常见的Lisp实现都支持CLOS 元对象协议.这提供了对类,插槽和其他元对象 的内省操作.

Many Common Lisp implementations support the CLOS Meta-object Protocol. This provides introspective operations for classes, slots and other meta objects.

在LispWorks中,可以直接在软件包CL-USER中访问相应的功能.

In LispWorks the corresponding functions are directly accessible in the package 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中找到它们.

The functions slot-definition-name and class-direct-slots are defined by the Meta Object Protocol for CLOS and are supported in many Common Lisp implementations - just the package they are in may differ. In SBCL for example one might find them in the package SB-MOP.

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

From a class we can get the list of direct slots. Direct slots are the slots which are directly defined for that class and which are not inherited. If you want to get a list of all slots, then use the function class-slots.

插槽在这里意味着我们得到了一个插槽定义对象,该对象描述了插槽.要获取插槽的名称,必须使用功能slot-definition-name从插槽定义对象中检索名称.

Slot here means that we get a slot definition object, which describes the slot. To get the name of the slot, you have to retrieve the name from the slot definition object using the function slot-definition-name.

这篇关于有没有办法获得一个班级的空缺?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆