我在看这行代码-
result = function(self, *args, **kwargs)
而且我找不到Python的function
关键字的定义。有人能把我链接到文档和/或解释一下这行代码的作用吗?我直觉上认为我知道,但我不明白为什么我找不到任何文档。
在搜索中http://docs.python.orgnew
模块及其后续类型似乎都与此有关。
function
不是python关键字。
如果稍微扩展一下视图,可以看到function
是一个变量(作为参数传入)。
def autoAddScript(function):
"""
Returns a decorator function that will automatically add it's result to the element's script container.
"""
def autoAdd(self, *args, **kwargs):
result = function(self, *args, **kwargs)
if isinstance(result, ClientSide.Script):
self(result)
return result
else:
return ClientSide.Script(ClientSide.var(result))
return autoAdd
在这种情况下,function
只是autoAddScript
函数的一个形式参数。它是一个局部变量,期望具有允许您像函数一样调用它的类型。
函数只是一个恰好是函数的变量也许举个简短的例子会更清楚:
def add(a,b):
return a+b
def run(function):
print(function(3,4))
>>> run(add)
7
首先,function
是python中的第一个类对象,这意味着您可以绑定到另一个名称,如fun = func()
,也可以将一个函数作为参数传递给另一个函数。
因此,让我们从一个小片段开始:
# I ve a function to upper case argument : arg
def foo(arg):
return arg.upper()
# another function which received argument as function,
# and return another function.
# func is same as function in your case, which is just a argument name.
def outer_function(func):
def inside_function(some_argument):
return func(some_argument)
return inside_function
test_string = 'Tim_cook'
# calling the outer_function with argument `foo` i.e function to upper case string,
# which will return the inner_function.
var = outer_function(foo)
print var # output is : <function inside_function at 0x102320a28>
# lets see where the return function stores inside var. It is store inside
# a function attribute called func_closure.
print var.func_closure[0].cell_contents # output: <function foo at 0x1047cecf8>
# call var with string test_string
print var(test_string) # output is : TIM_COOK