Common lisp 基于公共Lisp对象系统类定义中的其他插槽值初始化插槽
在我的类定义中,我想根据另一个插槽的值初始化一个插槽。以下是我想做的事情:Common lisp 基于公共Lisp对象系统类定义中的其他插槽值初始化插槽,common-lisp,clos,slot,Common Lisp,Clos,Slot,在我的类定义中,我想根据另一个插槽的值初始化一个插槽。以下是我想做的事情: (defclass my-class () ((slot-1 :accessor my-class-slot-1 :initarg slot-1) (slot-2 :accessor my-class-slot-2 :initform (list slot-1)))) 但是,这不会编译: 1 compiler notes: Unknown location: warning: This var
(defclass my-class ()
((slot-1 :accessor my-class-slot-1 :initarg slot-1)
(slot-2 :accessor my-class-slot-2 :initform (list slot-1))))
但是,这不会编译:
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.
有什么方法可以做到这一点吗?使用
初始化实例:在记录之后下面是Doug Currie的答案:
(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))))
以下是一个显示其有效性的电话:
> (my-class-slot-2 (make-instance 'my-class :slot-1 "Bob"))
("Bob")
更多详细信息,请参见。Zach Beane也在comp.lang.lisp上给出了这个答案(或者说几乎是类似的答案),但我在输入自己的代码之前没有注意到。谢谢扎克和道格!使用structs是否可以实现这一点或类似的功能?
(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>