为什么 `class-name` 在这种情况下在 REPL 中不起作用?

问题描述 投票:0回答:2

我正在阅读 Sonja Keene 的书 Common Lisp 中的面向对象编程

在第 7 章中,作者提出:

(class-name class-object)

这使得查询类对象的名称成为可能。

使用SBCL和SLIME的REPL,我尝试过:

; SLIME 2.26.1
CL-USER> (defclass stack-overflow () 
           ((slot-1 :initform 1 )
            (slot-2 :initform 2)))
#<STANDARD-CLASS COMMON-LISP-USER::STACK-OVERFLOW>
CL-USER> (make-instance 'stack-overflow)
#<STACK-OVERFLOW {1002D188E3}>
CL-USER> (defvar test-one (make-instance 'stack-overflow))
TEST-ONE
CL-USER> (slot-value test-one 'slot-1)
1
CL-USER> (class-name test-one)
; Evaluation aborted on #<SB-PCL::NO-APPLICABLE-METHOD-ERROR {10032322E3}>.

上面的代码返回以下错误消息:

There is no applicable method for the generic function
  #<STANDARD-GENERIC-FUNCTION COMMON-LISP:CLASS-NAME (1)>
when called with arguments
  (#<STACK-OVERFLOW {1003037173}>).
   [Condition of type SB-PCL::NO-APPLICABLE-METHOD-ERROR]

如何正确使用

class-name

谢谢。

oop common-lisp
2个回答
5
投票

class-name
的参数必须是类对象,而不是类的实例。

使用

class-of
获取实例的类,然后就可以调用
class-name

(class-name (class-of test-one))

0
投票

使用@Barmar对评论的提示,这将是正确的方法

class-name

CL-USER> (class-name (defclass stack-overflow () 
                       ((slot-1 :initform 1 )
                        (slot-2 :initform 2))))
STACK-OVERFLOW

class-name
接收一个类作为参数。为了使用实例,正确的方法是使用
class-of
:

CL-USER> (class-of 'test-one)
#<BUILT-IN-CLASS COMMON-LISP:SYMBOL>

但我不确定为什么

class-name
会有帮助。

© www.soinside.com 2019 - 2024. All rights reserved.