Python函数中的关键字是用来干什么的?

3

我正在看这一行代码 - (链接)

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

我找不到 Python 中关于 function 关键字的定义。有人能给我提供相关文档的链接和/或解释一下这行代码的含义吗?我有直觉地认为我知道它的含义,但我不理解为什么我找不到任何相关文档。
在搜索了 http://docs.python.org 后,新模块(new module)以及它的继承者类型模块(types似乎与此有关。

3
在Python中,function不是一个关键字。 - Ashwini Chaudhary
在你的例子中,function 是父方法的一个参数,见https://github.com/metaperl/webelements/blob/master/WebElements/Base.py#L56 - Jakob
这似乎更像是一个如何使用函数的示例,而不是一个实际的函数。 - kylieCatt
4个回答

8

这是因为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函数的形式参数。它是一个局部变量,预期具有一种类型,使您可以像调用函数一样调用它。

3

函数只是一个变量,它恰好是一个函数而已。也许通过一个简短的例子更容易理解:

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

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

>>> run(add)
7

2

首先,在Python中,function是一等对象,这意味着您可以将其绑定到另一个名称,例如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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接