基于Common Lisp中的对象系统的类定义其他槽值初始化插槽
-
26-09-2019 - |
题
在我的类定义,我想基于另一槽的值来初始化一个时隙。这里是诸如此类的事情,我想这样做:
(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.
有没有办法做到这一点?
解决方案
使用initialize-instance :after
记录这里
其他提示
下面是道格库里的回答扩展:
(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")
请参阅这篇文章更多的细节。
(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>
不隶属于 StackOverflow