Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
583 views
in Technique[技术] by (71.8m points)

common lisp - Is there a way to get the slots of a class?

I have a class like this one

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

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

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)

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.

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 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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...