在view.generic.base中的视图的django中有类定义
class View(object):
...
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
return self.dispatch(request, *args, **kwargs)
# take name and docstring from class
update_wrapper(view, cls, updated=())
# and possible attributes set by decorators
# like csrf_exempt from dispatch
update_wrapper(view, cls.dispatch, assigned=())
return view
它应该返回一个像view(request,* args,** kwargs)这样的函数。
请注意'def视图'中有一个变量,即'cls'。
假设我们运行:
tmp = View.as_view(),tmp(request,* args,** kwargs)将如何知道cls的值是多少?
这是简化的情况!!!!!
说像这样的python代码:
>>> def func1(a):
... def func2(b):
... c = a + b
... print c
... return func2
...
>>> func3 = func1(3)
>>> func3(1)
4
>>> func4 = func1(4)
>>> func3(1)
4
>>> func4(1)
5
>>> func3.a=5
>>> func3(1)
4
>>> func1.a=5
>>> func3(1)
4
实际上def在func3中的'a'是什么?func3是如何得到它的?
UPDATE1:
谢谢回答。问题没有完全表达出来。
我想,当我们调用func3 = func1(3)时,我们在程序中有两个对象,func1的代码,被称为func1(3)的对象(符号表)。
我的问题是:
是否有通过调用代码func1()生成的func2()对象,或者func3的值只是指向生成的func1(3)的成员的指针,该函数是func2()的指令?
是在func1(3)中调用func3(1)的a,还是func2()的对象?
您已通过从另一个函数返回函数来创建闭包。
使用简化示例,只要func2继续存在,任何在范围内并且从内部函数func2引用的变量将保留在范围内。
因此,即使在func1结束之后,func2内的任何变量(包括a等函数参数)都可以访问func2。
a运行时a具有的值将是您传递给func1以生成func2的特定实例的任何值
让我解释一下你的代码是做什么的
>>> def func1(a):
... def func2(b):
... c = a + b
... print c
... return func2
...
这将创建一个函数func1,它返回另一个函数func2。 func2是func1的本地
>>> func3 = func1(3)
这将创建变量func3,func3的值为func2。因此,当您打印func3的值时,它将返回功能。
>>> func3
如果您尝试访问func3.a,则它不会返回1,因为a不是func2的属性。
>>> func3.a
Traceback (most recent call last):
File"", line 1, in
AttributeError: 'function' object has no attribute 'a'
a是局部变量,因此您无法访问它。当您调用func3时,它将func2调用func2作为1。
>>> func3(1)
4
因此,这将调用func2(1),其中a在本地func2中3。
我运行相同的python程序并进行了一些更改:
>>> def func1(a):
... def func2(b):
... c = a + b
... print c
... print a
... print b
... return func2
...
>>> func3 = func1(3)
>>> func3(1)
4
3
1
首先,当你调用fun1(3)时,fun1返回fun2,就像这样
def fun2(b):
c = 3 + b
print c
print 3
print b
2.现在,当你调用函数func3(1)时,你实际上是在调用func2(1)
这是应该工作的方式:)
首先,这里没有任何递归,我想你的意思是内部函数定义。内部函数可以访问周围的范围(也称为闭包)。获得函数func3的副本后,它将可以访问外部函数中定义的变量,包括调用它的参数