2014-01-29 22 views
0

我看this line of code -Python函數關鍵字有什麼作用?

result = function(self, *args, **kwargs) 

而且我沒能找到function關鍵字爲Python的定義。有人可以鏈接我的文檔和/或解釋,這行代碼呢?我直覺地認爲我知道,但我不明白爲什麼我找不到任何文檔。

在搜尋http://docs.python.orgthe new module及其後繼者types似乎與它有關。

+2

'function'並不是一個Python關鍵字。 –

+0

在你的例子中'function'是父方法的一個參數,見https://github.com/metaperl/webelements/blob/master/WebElements/Base.py#L56 – Jakob

+0

看起來更像是一個你將如何使用的例子一個功能比實際功能。 – IanAuld

回答

5

這是因爲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 
4

在這種情況下function只是一個形式參數的autoAddScript功能。這是一個本地變量,預計會有一個類型,允許您將它稱爲函數。

1

功能只是碰巧是一個函數 可能與一個簡單的例子這將是更清晰的變量:

def add(a,b): 
    return a+b 

def run(function): 
    print(function(3,4)) 

>>> run(add) 
7 
1

所有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 
相關問題