【发布时间】:2017-02-17 02:18:01
【问题描述】:
在您将其标记为重复之前,让我声明我了解 super 的工作原理,并且我已阅读以下三个链接:
What does 'super' do in Python?
Understanding Python super() with __init__() methods
http://python-history.blogspot.nl/2010/06/method-resolution-order.html
这就是super 在baseclasses 的情况下应该如何工作:
class X(object):
def __init__(self):
print "calling init from X"
super(X, self).__init__()
class Y(object):
def abc(self):
print "calling abc from Y"
super(Y, self).abc()
a = X()
# prints "calling init from X" (works because object possibly has an __init__ method)
b = Y()
b.abc()
# prints "calling abc from Y" and then
# throws error "'super' object has no attribute 'abc'" (understandable because object doesn't have any method named abc)
问题:在django 核心实现中,有几个地方在从object 继承的类上使用super 调用methods(在上面的示例中为Y) .例如:有人能解释一下为什么这段代码有效吗?
from django.core.exceptions import PermissionDenied
class LoginRequiredMixin(object):
def dispatch(self, request, *args, **kwargs):
if not request.user.is_authenticated():
raise PermissionDenied
return super(LoginRequiredMixin, self).\
dispatch(request, *args, **kwards) # why does this work?
参考:从这次谈话中复制了这段代码:https://youtu.be/rMn2wC0PuXw?t=403
【问题讨论】: