在“学习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)
does?
虽然这种嵌套对我来说看起来肯定不像是好的、可用的代码,但 Python 仍然认为它是有效的,所以我很好奇如何调用它。
你得到一个TypeError
因为功能func
不返回任何东西(因此它的返回是NoneType
)。它应该返回subfunc
:
>>> def superfunc(X):
... def func(Y):
... def subfunc(Z):
... return X + Y + Z
... return subfunc
... return func
...
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)