具有多个参数括号的 Python 函数

标签 python function

我一直无法理解 h(a)(b) 的含义。在昨天之前我从未见过其中之一,而且我无法以这种方式声明函数:

def f (a)(b):
    return a(b)

当我尝试执行 def f (a, b): 时,它也不起作用。这些函数做什么?我该如何声明它们?最后,f(a, b)f(a)(b)之间<​​strong>有什么区别?

最佳答案

不存在具有多个参数括号的函数,正如您在尝试定义一个时看到的那样。但是,有些函数会返回(其他)函数:

def func(a):
    def func2(b):
        return a + b
    return func2

现在,当您调用 func() 时,它会返回内部 func2 函数:

>>> func2 = func(1)  # You don't have to call it func2 here
>>> func2(2)
3

但是如果你以后不需要内部函数,那么就没有必要将它保存到一个变量中,你可以一个接一个地调用它们:

>>> func(1)(2)   # func(1) returns func2 which is then called with (2)
3

在定义带参数的装饰器时,这是一个非常常见的习惯用法。


请注意,调用 func() 总是会创建一个 new 内部函数,即使它们在定义中都被命名为 func2我们的 func:

>>> f1 = func(1)
>>> f2 = func(1)
>>> f1(1), f2(1)
(2, 2)
>>> f1 is f2
False

And, finally, what's the difference between f(a, b)and f(a)(b)?

现在应该清楚你知道 f(a)(b) 做了什么,但总结一下:

  • f(a, b) 调用 f 有两个参数 ab
  • f(a)(b) 用一个参数 a 调用 f,然后返回另一个函数,然后用一个参数调用该函数参数b

关于具有多个参数括号的 Python 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42874825/

相关文章:

JavaScript:带有回调和参数的事件监听器

python - 在连通分量标记函数后计算图像矩

Python:跟踪文本文件中的当前列

python - 为什么我得到 "AttributeError: ' unicode' object has no attribute 'user' "on some specified url only only?

c - Arduino:函数错误的重新定义

python - 在 python 中,函数应该更改列表还是制作副本并返回?

c++ - 我可以在父构造函数中多次重用函数的返回值吗?

python - QMetaObject::invokeMethod 找不到带参数的方法

python - 如何将python编译成可执行文件?

python - 如何在 Python 中迭代 N 级嵌套字典?