ClassName(object)中的super(ClassName,self)有什么作用? (用于django docs)

时间:2013-03-22 19:30:57

标签: python django

以下代码实际上来自Django documentation about forms in class-based views

import json

from django.http import HttpResponse
from django.views.generic.edit import CreateView

class AjaxableResponseMixin(object):
    """
    Mixin to add AJAX support to a form.
    Must be used with an object-based FormView (e.g. CreateView)
    """
    def render_to_json_response(self, context, **response_kwargs):
        data = json.dumps(context)
        response_kwargs['content_type'] = 'application/json'
        return HttpResponse(data, **response_kwargs)

    def form_invalid(self, form):
        if self.request.is_ajax():
            return self.render_to_json_response(form.errors, status=400)
        else:
            return super(AjaxableResponseMixin, self).form_invalid(form)

    def form_valid(self, form):
        if self.request.is_ajax():
            data = {
                'pk': form.instance.pk,
            }
            return self.render_to_json_response(data)
        else:
            return super(AjaxableResponseMixin, self).form_valid(form)

class AuthorCreate(AjaxableResponseMixin, CreateView):
    model = Author

我不理解的代码是super(AjaxableResponseMixin, self)。我知道super(ChildClass, self)用于在子类的代码中调用父类的方法。但AjaxableResponseMixin没有任何父母!这是做什么的?

1 个答案:

答案 0 :(得分:4)

AuthorCreate中,AjaxableResponseMixin的超类将为CreateView

>>> class a(object): pass
... 
>>> class b(object): pass
... 
>>> class c(a,b): pass
... 
>>> c.mro()
[<class '__main__.c'>, <class '__main__.a'>, <class '__main__.b'>, <type 'object'>]

mro()是“方法解析顺序”,即super引用的顺序。