La inicialización de ranuras sobre la base de otros valores de slot en las definiciones de clase de sistema Common Lisp Object

StackOverflow https://stackoverflow.com/questions/3620249

  •  26-09-2019
  •  | 
  •  

Pregunta

En mi definición de clase, quiero inicializar una ranura en base al valor de la otra ranura. Aquí es el tipo de cosa que me gustaría hacer:

(defclass my-class ()
  ((slot-1 :accessor my-class-slot-1 :initarg slot-1)
   (slot-2 :accessor my-class-slot-2 :initform (list slot-1))))

Sin embargo, esto no se compila:

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.

¿Hay una manera de hacer esto?

Otros consejos

Aquí está la respuesta de Doug Currie amplió:

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

Aquí hay una llamada que demuestra que funciona:

> (my-class-slot-2 (make-instance 'my-class :slot-1 "Bob"))
("Bob")

este artículo para más detalles.

(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> 
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top