【问题标题】:Initializing slots based on other slot values in Common Lisp Object System class definitions根据 Common Lisp Object System 类定义中的其他槽值初始化槽
【发布时间】:2010-09-01 16:37:44
【问题描述】:

在我的类定义中,我想根据另一个槽的值来初始化一个槽。这是我想做的事情:

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

有没有办法做到这一点?

【问题讨论】:

    标签: common-lisp clos slot


    【解决方案1】:

    使用initialize-instance :after记录的here

    【讨论】:

    • 是否可以使用结构体或类似的方法?
    【解决方案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")
    

    更多详情请见this article

    【讨论】:

    • Zach Beane 在 comp.lang.lisp 上也给出了这个答案(或一个几乎类似的答案),但在输入我自己的代码之前我没有注意到它。感谢 Zach 和 Doug!
    【解决方案3】:
    (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> 
    

    【讨论】:

      猜你喜欢
      • 2020-04-05
      • 2021-12-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-08-26
      相关资源
      最近更新 更多