[英]What does the Python function keyword do?
我正在看這行代碼 -
result = function(self, *args, **kwargs)
而且我找不到Python的function
關鍵字的定義。 有人可以將我鏈接到文檔和/或解釋這行代碼嗎? 我直覺上以為我知道,但是我不明白為什么我找不到關於它的任何文檔。
在http://docs.python.org中進行搜索時, new
模塊及其后繼類型都與它有關。
那是因為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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.