【问题标题】:How to use call-next-method in initialize-instance with multiple key arguments CLOS如何在具有多个关键参数 CLOS 的初始化实例中使用 call-next-method
【发布时间】:2020-11-27 20:08:34
【问题描述】:

如果我有两个班级,一个班级parent 和一个班级child

(defclass parent ()
    ...)

(defclass child (parent)
    ...)

我已经为初始化实例定义了 2 种不同的方法,但是孩子接受另一个参数,并调用 call-next-method

(defmethod initialize-instance :after ((instance parent) &key)
    ...) ; Do things

(defmethod initialize-instance :after ((instance child) &key other-arg)
    ... ; Do things
    (call-next-method))

我得到了错误

There is no next method for the generic function
#<STANDARD-METHOD COMMON-LISP:INITIALIZE-INSTANCE (93)>
when called from method
#<STANDARD-METHOD COMMON-LISP:INITIALIZE-INSTANCE :AFTER (CHILD) {...}>
with arguments
 ....

Condition of type SB-PCL::NO-NEXT-METHOD-ERROR

显然,我无法使用提供的参数调用下一个方法?

【问题讨论】:

    标签: common-lisp clos


    【解决方案1】:

    在你使用的standard method combination中,after方法没有next方法,所以call-next-method不能在其中使用:相当适用after方法都在most-specific-last中调用按方法组合排序。你被允许使用call-next-method的地方是主要的和周边的方法。

    【讨论】:

      【解决方案2】:

      可能是您引用了帖子中未提及的方法吗?错误消息提到了:after 方法。也许您可以启动一个新的 sbcl 实例并在那里重新创建类和方法,以确保同样的问题仍然存在?

      我尝试像这样填写您代码中的空白:

      (defclass parent ()
        nil)
      
      (defclass child (parent)
        nil)
      
      (defmethod initialize-instance ((instance parent) &key)
        (format t "~&Init parent."))
      
      (defmethod initialize-instance ((instance child) &key other-arg)
        (format t "Init child with ~a." other-arg)
        (call-next-method))
      
      CL-USER> (make-instance 'parent)
      Init parent.
      #<PARENT {100390DEE3}>
      CL-USER> (make-instance 'child)
      Init child with NIL.
      Init parent.
      #<CHILD {100390AB93}>
      CL-USER> (make-instance 'child :other-arg 'foo)
      Init child with FOO.
      Init parent.
      #<CHILD {100396D253}>
      

      以上似乎适用于我的设置。
      对你有用吗?

      【讨论】:

      • 这是一个玩具示例,我没有测试它。好的,所以问题不在于这里。我要编辑问题。
      • 我忘了在方法中添加:after
      猜你喜欢
      • 2017-08-27
      • 2018-03-06
      • 2016-06-14
      • 2018-03-03
      • 2010-10-23
      • 1970-01-01
      • 2017-05-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多