class-of
class-of Function
Syntax:
class-of object ! class
Arguments and Values:
object—an object.
class—a class object.
Description:
Returns the class of which the object is a direct instance.
Examples:
(class-of ’fred) *!* #<BUILT-IN-CLASS SYMBOL 610327300>
(class-of 2/3) *!* #<BUILT-IN-CLASS RATIO 610326642>
(defclass book () ()) *!* #<STANDARD-CLASS BOOK 33424745>
(class-of (make-instance ’book)) *!* #<STANDARD-CLASS BOOK 33424745>
(defclass novel (book) ()) *!* #<STANDARD-CLASS NOVEL 33424764>
(class-of (make-instance ’novel)) *!* #<STANDARD-CLASS NOVEL 33424764>
(defstruct kons kar kdr) *!* KONS
(class-of (make-kons :kar 3 :kdr 4)) *!* #<STRUCTURE-CLASS KONS 250020317>
See Also:
make-instance, type-of
Expanded Reference: class-of
Querying the Class of Built-In Objects
class-of returns the class of which the given object is a direct instance.
(class-of 42)
==> #<BUILT-IN-CLASS FIXNUM>
(class-of "hello")
==> #<BUILT-IN-CLASS SIMPLE-BASE-STRING>
(class-of 'foo)
==> #<BUILT-IN-CLASS SYMBOL>
(class-of #\a)
==> #<BUILT-IN-CLASS CHARACTER>
(class-of '(1 2 3))
==> #<BUILT-IN-CLASS CONS>
Querying the Class of CLOS Instances
For user-defined classes, class-of returns the class created by defclass.
(defclass animal ()
((name :initarg :name)))
(defclass dog (animal) ())
(let ((d (make-instance 'dog :name "Rex")))
(class-name (class-of d)))
=> DOG
Comparing class-of with typep
class-of returns the most specific (direct) class, while typep checks membership in a class and all its superclasses.
(defclass shape () ())
(defclass circle (shape) ())
(let ((c (make-instance 'circle)))
(list (class-name (class-of c)) ;; Direct class
(typep c 'circle) ;; Is a circle
(typep c 'shape) ;; Is also a shape
(typep c 'standard-object)));; Is also a standard-object
=> (CIRCLE T T T)
Using class-of with Structures
Structure types defined with defstruct also have classes.
(defstruct point x y)
(let ((p (make-point :x 1 :y 2)))
(class-name (class-of p)))
=> POINT