Skip to main content
 首页 » 编程设计

python之如何在 python 中使用 (var1)(var2) 表示法将函数应用于值

2025年05月04日9haluo1

我正在用 python 解决几个问题 在其中一个中,它要求我编写一个函数,这样当 examplefunction([1, 2, 3, 4])(10) 返回一些东西让我们说 10。

问题是,到目前为止,我从未见过在 python 中使用双 ()() 来调用函数的符号。

我已经尝试查看有关堆栈溢出的多个帖子,例如 Python: Apply function to values in nested dictionary

但是这样的问题真的没有。

请您参考如下方法:

object()() 只是 _result = object() 和 _result() 链接在一起。只要第一个调用返回一个可调用对象,第二个调用表达式就可以继续。

让您的 examplefunction() 调用返回另一个函数。函数也是对象,因此您可以只返回一个现有函数:

def examplefunction(): 
    return secondfunction 
 
def secondfunction(): 
    return 10 

此时 examplefunction()() 生成 10。

您还可以让您的 examplefunction() 调用每次都生成一个新的函数对象,方法是将该函数对象定义为其主体的一部分:

def examplefunction(): 
    def nestedfunction(): 
        return 10 
    return nestedfunction 

这给出了相同的结果,但是 nestedfunction() 具有(读取)访问 examplefunction 中定义的所有本地名称的附加优势(这些称为 闭包);这允许您参数化 nestedfunction() 的行为方式:

def examplefunction(base): 
    def nestedfunction(): 
        return base * 2 
    return nestedfunction 
 
examplefunction(5)()  # produces 10 

我怀疑你的作业是想教你这些原则。