खोज…


किसी क्लास के स्लॉट नामों को प्राप्त करें

हम कहते हैं कि हमारे पास एक वर्ग है

(defclass person ()
  (name email age))

क्लास के स्लॉट्स के नाम प्राप्त करने के लिए हम फंक्शन क्लास-स्लॉट्स का उपयोग करते हैं। यह करीब-एमओपी पैकेज में पाया जा सकता है, जो करीब-मोप प्रणाली द्वारा प्रदान किया जाता है। इसे चलाने वाली लिस्प इमेज को लोड करने के लिए हम उपयोग करते हैं (ql:quickload :closer-mop) । हमें यह भी सुनिश्चित करना होगा कि क्लास-स्लॉट्स को कॉल करने से पहले क्लास को अंतिम रूप दिया जाए।

(let ((class (find-class 'person)))
  (c2mop:ensure-finalized class)
  (c2mop:class-slots class))

जो प्रभावी स्लॉट परिभाषा वस्तुओं की एक सूची देता है:

(#<SB-MOP:STANDARD-EFFECTIVE-SLOT-DEFINITION S/TRANSFORMATIONS::NAME>
 #<SB-MOP:STANDARD-EFFECTIVE-SLOT-DEFINITION S/TRANSFORMATIONS::EMAIL>
 #<SB-MOP:STANDARD-EFFECTIVE-SLOT-DEFINITION S/TRANSFORMATIONS::AGE>)

एक स्लॉट को अपडेट करें जब दूसरा स्लॉट संशोधित हो

CLOS MOP हुक स्लॉट-वैल्यू-यूज़िंग-क्लास प्रदान करता है, जिसे तब कहा जाता है जब किसी स्लॉट को एक्सेस किया जाता है, पढ़ा या संशोधित किया जाता है। क्योंकि हम केवल इस मामले में संशोधनों के लिए परवाह करते हैं, हम (setf slot-value-using-class) लिए एक विधि को परिभाषित (setf slot-value-using-class)

(defclass document ()
  ((id :reader id :documentation "A hash computed with the contents of every other slot")
   (title :initarg :title :accessor title)
   (body :initarg :body :accessor body)))

(defmethod (setf c2mop:slot-value-using-class) :after
    (new class (object document) (slot c2mop:standard-effective-slot-definition))
  ;; To avoid this method triggering a call to itself, we check that the slot
  ;; the modification occurred in is not the slot we are updating.
  (unless (eq (slot-definition-name slot) 'id)
    (setf (slot-value object 'id) (hash-slots object))))

ध्यान दें कि उदाहरण के लिए सृजन slot-value नहीं होने के कारण कोड को initialize-instance :after में डुप्लिकेट करना आवश्यक हो सकता है initialize-instance :after विधि के initialize-instance :after

(defmethod initialize-instance :after ((obj document) &key)
  (setf (slot-value obj 'id)
        (hash-slots obj)))


Modified text is an extract of the original Stack Overflow Documentation
के तहत लाइसेंस प्राप्त है CC BY-SA 3.0
से संबद्ध नहीं है Stack Overflow