首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >基于Common Lisp对象系统类定义中的其他槽值初始化槽

基于Common Lisp对象系统类定义中的其他槽值初始化槽
EN

Stack Overflow用户
提问于 2010-09-02 00:37:45
回答 3查看 2K关注 0票数 6

在我的类定义中,我希望根据一个插槽的值初始化另一个插槽。下面是我想做的事情:

代码语言:javascript
复制
(defclass my-class ()
  ((slot-1 :accessor my-class-slot-1 :initarg slot-1)
   (slot-2 :accessor my-class-slot-2 :initform (list slot-1))))

然而,这不能编译:

代码语言:javascript
复制
1 compiler notes:

Unknown location:
  warning: 
    This variable is undefined:
      SLOT-1

  warning: 
    undefined variable: SLOT-1
    ==>
      (CONS UC-2::SLOT-1 NIL)


Compilation failed.

有没有办法做到这一点?

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2010-09-02 00:53:02

使用initialize-instance :after文档记录的here

票数 3
EN

Stack Overflow用户

发布于 2010-09-02 01:37:13

以下是道格·柯里的扩展答案:

代码语言:javascript
复制
(defclass my-class ()
  ((slot-1 :accessor my-class-slot-1 :initarg :slot-1)
   (slot-2 :accessor my-class-slot-2)))

(defmethod initialize-instance :after 
           ((c my-class) &rest args)
  (setf (my-class-slot-2 c) 
        (list (my-class-slot-1 c))))

下面的调用说明了它是有效的:

代码语言:javascript
复制
> (my-class-slot-2 (make-instance 'my-class :slot-1 "Bob"))
("Bob")

有关更多详细信息,请参阅this article

票数 2
EN

Stack Overflow用户

发布于 2010-09-02 06:19:50

代码语言:javascript
复制
(defparameter *self-ref* nil)


(defclass self-ref ()
  ()

  (:documentation "
Note that *SELF-REF* is not visible to code in :DEFAULT-INITARGS."))


(defmethod initialize-instance :around ((self-ref self-ref) &key)
  (let ((*self-ref* self-ref))
    (when (next-method-p)
      (call-next-method))))



(defclass my-class (self-ref)
  ((slot-1 :accessor slot-1-of :initarg :slot-1)
   (slot-2 :accessor slot-2-of
           :initform (slot-1-of *self-ref*))))




CL-USER> (let ((it (make-instance 'my-class :slot-1 42)))
           (values (slot-1-of it)
                   (slot-2-of it)))
42
42
CL-USER> 
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/3620249

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档