gpt4 book ai didi

lisp - ( :before/:after) method invocation in CLOS? 的顺序

转载 作者:太空宇宙 更新时间:2023-11-03 18:41:57 31 4
gpt4 key购买 nike

我需要一些帮助来理解以下代码的执行顺序。

我创建了一个 pie 的实例,使用以下内容:

(cook (make-instance 'pie))

我知道 lisp 从最具体到最不具体的顺序执行函数。但是,它看起来不像是在 (defmethod cook ((p pie)) 之后被遵循的。叫做。

我假设 (defmethod cook :after ((f food)) & (defmethod cook :after ((p pie))以相反的顺序执行,因为我们的实例是 pie ,而不是父类,food .

谢谢,任何输入将不胜感激。

(defclass food () ())

(defmethod cook :before ((f food))
(print "A food is about to be cooked."))

(defmethod cook :after ((f food))
(print "A food has been cooked."))

(defclass pie (food)
((filling :accessor pie-filling
:initarg :filling
:initform 'apple)))

(defmethod cook ((p pie))
(print "Cooking a pie.")
(setf (pie-filling p) (list 'cooked (pie-filling p))))

(defmethod cook :before ((p pie))
(print "A pie is about to be cooked."))

(defmethod cook :after ((p pie))
(print "A pie has been cooked."))
(setq pie-1 (make-instance 'pie :filling 'apple))

输出如:

"A pie is about to be cooked." 
"A food is about to be cooked."
"Cooking a pie."
"A food has been cooked."
"A pie has been cooked."
(COOKED APPLE)

最佳答案

参见 section 7.6.6.2 (Standard Method Combination) of the Common Lisp HyperSpec .这是最相关的段落:

The before methods are run in most-specific-first order while the after methods are run in least-specific-first order. The design rationale for this difference can be illustrated with an example. Suppose class C1 modifies the behavior of its superclass, C2, by adding before methods and after methods. Whether the behavior of the class C2 is defined directly by methods on C2 or is inherited from its superclasses does not affect the relative order of invocation of methods on instances of the class C1. Class C1's before method runs before all of class C2's methods. Class C1's after method runs after all of class C2's methods.

关于lisp - ( :before/:after) method invocation in CLOS? 的顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8371820/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com