1. 多继承
- 首先要清楚: __mro__ 即 继承顺序
1.1 单继承实现:

1.2 多继承实现:

- 程序 从 A 开始调用,虽然貌似B 继承了 object 类,但是super(),会按照 __mro__顺序去查找,而在这里 调用发生在A身上,所以__mro__ 属于A,那么,按顺序 B 会从C找 as_view() 方法,而不是 object 。
要知道 object 身上 是没有 as_view()方法的,少年!
源码原理(class: view):
@classonlymethod
def as_view(cls, **initkwargs):
"""
Main entry point for a request-response process.
"""
...省略代码...
def view(request, *args, **kwargs):
self = cls(**initkwargs)
if hasattr(self, 'get') and not hasattr(self, 'head'):
self.head = self.get
self.request = request
self.args = args
self.kwargs = kwargs
# 调用dispatch方法,按照不同请求方式调用不同请求方法
return self.dispatch(request, *args, **kwargs)
...省略代码...
# 返回真正的函数视图
return view
def dispatch(self, request, *args, **kwargs):
# Try to dispatch to the right method; if a method doesn't exist,
# defer to the error handler. Also defer to the error handler if the
# request method isn't on the approved list.
if request.method.lower() in self.http_method_names:
handler = getattr(self, request.method.lower(), self.http_method_not_allowed)
else:
handler = self.http_method_not_allowed
return handler(request, *args, **kwargs)
网友评论