代码之家  ›  专栏  ›  技术社区  ›  Paul Reiners

基于通用Lisp对象系统类定义中的其他槽值初始化槽

  •  5
  • Paul Reiners  · 技术社区  · 15 年前

    在我的类定义中,我想基于另一个槽的值初始化一个槽。下面是我想做的事情:

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

    有办法吗?

    3 回复  |  直到 15 年前
        1
  •  3
  •   Doug Currie    15 年前

    使用 initialize-instance :after 文件化的 here

        2
  •  2
  •   Paul Reiners    15 年前

    下面是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 了解更多详细信息。

        3
  •  2
  •   lnostdal    15 年前
    (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> 
    
    推荐文章