Initialisieren von Schlitzen auf der Grundlage anderer Schlitzwerte in Common Lisp Objektdefinitionen System-Klasse
-
26-09-2019 - |
Frage
In meiner Klasse Definition, möchte ich einen Schlitz initialisieren, basierend auf dem Wert eines anderen Steckplatz. Hier ist das, was würde ich tun:
(defclass my-class ()
((slot-1 :accessor my-class-slot-1 :initarg slot-1)
(slot-2 :accessor my-class-slot-2 :initform (list slot-1))))
Dies gilt jedoch nicht kompilieren:
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.
Gibt es eine Möglichkeit, dies zu tun?
Lösung
Mit initialize-instance :after
dokumentiert hier
Andere Tipps
Hier ist Doug Currie Antwort erweitert:
(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))))
Hier ist ein Aufruf zeigt, dass es funktioniert:
> (my-class-slot-2 (make-instance 'my-class :slot-1 "Bob"))
("Bob")
Siehe dieser Artikel für weitere Details.
(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>
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow