简体   繁体   English

我何时应该在python的基类中使用关键字super?

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

I am trying to understand this piece of code in python. 我正在尝试理解python中的这段代码 From my understanding, super is used to call a base class function from derived class when you don't want to explicitly write the name of the base class. 根据我的理解,当您不想显式编写基类的名称时,可以使用super从派生类中调用基类函数。 But as mentioned below, what does it mean if the base class itself uses super to call some function? 但是,如下所述,如果基类本身使用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)

I tried creating few sample classes like above but I get the expected "no such parameter" exception. 我尝试创建像上面这样的几个示例类,但是得到了预期的“无此类参数”异常。

You'll notice that your class ReviewCreateView has two (direct) base classes. 您会注意到您的类ReviewCreateView具有两个 (直接)基类。 super is necessary to make sure that the dispatch method gets called on both of those base classes. super是必需的,以确保在这两个基类上调用了dispatch方法。

Whenever a class is created, python looks at the inheritance tree and flattens it which creates something called the "Method Resolution Order" (MRO) . 每当创建类时,python都会查看继承树并将其展平,这将创建一个称为“方法解析顺序”(MRO)的东西 In this case, your MRO is probably 1 : 在这种情况下,您的MRO可能为1

ReviewCreateView, ReviewViewMixin, CreateView, ..., object

What super does is it inspects the current MRO and it calls the method on the next class in the MRO. super所做的是检查当前的MRO,并在MRO中的下一个类上调用该方法。 Your call stack will look like: 您的调用堆栈将如下所示:

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

Now note that if ReviewViewMixin didn't have a super in there, the call stack would have ended with it. 现在请注意,如果ReviewViewMixin没有super ReviewViewMixin ,则调用堆栈将ReviewViewMixin结束。 However, since it has a super and the next class in the MRO is CreateView , CreateView 's dispatch method will also get called. 然而,由于它具有super ,并在MRO下一堂课是CreateViewCreateView的分配方法也将被调用。

super can be tricky to really wrap your head around -- I'd suggest reading the "super is Super" article by Raymond Hettinger for some ideas and best-practices. super要真正动脑筋可能很棘手-我建议阅读Raymond Hettinger的“超级就是超级”文章,以获取一些想法和最佳实践。

1 You can inspect the MRO by using inspect.getmro(ReviewCreateView) or simply looking at ReviewCreateView.__mro__ 1您可以通过使用inspect.getmro(ReviewCreateView)或仅查看ReviewCreateView.__mro__来检查MRO ReviewCreateView.__mro__

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM