gpt4 book ai didi

Python 深层嵌套工厂函数

转载 作者:行者123 更新时间:2023-11-28 20:08:45 24 4
gpt4 key购买 nike

在学习“学习 Python”时遇到了工厂函数。这个教科书示例有效:

def maker(N):
def action(X):
return X ** N
return action


>>> maker(2)
<function action at 0x7f9087f008c0>
>>> o = maker(2)
>>> o(3)
8
>>> maker(2)
<function action at 0x7f9087f00230>
>>> maker(2)(3)
8

然而,当深入另一个层次时,我不知道如何调用它:

>>> def superfunc(X):
... def func(Y):
... def subfunc(Z):
... return X + Y + Z
... return func
...
>>> superfunc()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: superfunc() takes exactly 1 argument (0 given)
>>> superfunc(1)
<function func at 0x7f9087f09500>
>>> superfunc(1)(2)
>>> superfunc(1)(2)(3)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'NoneType' object is not callable
>>> superfunc(1)(2)
>>>

为什么 superfunc(1)(2)(3) 不能工作而 maker(2)(3) 可以?

虽然这种嵌套在我看来肯定不是好的、可用的代码,但 Python 仍然接受它是有效的,所以我很好奇如何调用它。

最佳答案

你得到一个 TypeError 因为函数 func 没有返回任何东西(因此它的返回是 NoneType)。它应该返回 subfunc:

>>> def superfunc(X):
... def func(Y):
... def subfunc(Z):
... return X + Y + Z
... return subfunc
... return func
...

关于Python 深层嵌套工厂函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12687277/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com