6

私のクラス定義では、あるスロットを別のスロットの値に基づいて初期化したいと考えています。これが私がやりたいことのようなものです:

(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.

これを行う方法はありますか?

4

3 に答える 3

3

ここにinitialize-instance :after文書化された使用

于 2010-09-01T16:53:02.017 に答える
2
(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> 
于 2010-09-01T22:19:50.370 に答える
2

これが 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")

詳細については、この記事を参照してください。

于 2010-09-01T17:37:13.427 に答える