簡體   English   中英

Python函數關鍵字有什么作用?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM