什么时候应该在 python 中的 Base class 中使用关键字 super?

When should I use the keyword super in Base class in python?

我正在尝试理解 python 中的 this piece of code。根据我的理解,super 用于从派生的 class 调用基 class 函数,当您不想显式写基 class 的名称时。但是如下所述,如果基class本身使用super来调用某个函数,这意味着什么?

class ReviewViewMixin(object):
    def dispatch(self, request, *args, **kwargs):
        # some code
        return super(ReviewViewMixin, self).dispatch(request, *args, **kwargs)


class ReviewCreateView(ReviewViewMixin, CreateView):
    # some code
    def dispatch(self, request, *args, **kwargs):
        super(ReviewCreateView, self).dispatch(request, *args, **kwargs)

我尝试像上面那样创建几个样本 class,但我得到了预期的 "no such parameter" 异常。

您会注意到您的 class ReviewCreateView 两个 (直接)基础 class。 super 是必要的,以确保 dispatch 方法在 classes.

both 上被调用

每当创建 class 时,python 都会查看继承树并将其展平,从而创建称为 "Method Resolution Order" (MRO) 的东西。在这种情况下,您的 MRO 可能是 1:

ReviewCreateView, ReviewViewMixin, CreateView, ..., object

super 所做的是检查当前 MRO 并调用 MRO 中下一个 class 的方法。您的调用堆栈将如下所示:

ReviewCreateView.dispatch (super) -> ReviewViewMixin.dispatch (super) -> CreateView.dispatch

现在请注意,如果 ReviewViewMixin 中没有 super,调用堆栈将以它结束。但是,由于它有一个 super 并且 MRO 中的下一个 class 是 CreateViewCreateView 的调度方法也会被调用。

super 可能很难真正全神贯注——我建议阅读 Raymond Hettinger 的 "super is Super" 文章,了解一些想法和最佳实践。

1您可以使用 inspect.getmro(ReviewCreateView) 或简单地查看 ReviewCreateView.__mro__[=27 来检查 MRO =]