Python 深度嵌套工厂函数



通过"Learning 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
... 

superfunc某处缺少返回:您有一个subfuncreturn,但没有func的。

已更正 superfunc,并附有调用示例

def superfunc(X):
    def func(Y):
        def subfunc(Z):
            return X + Y + Z
        return subfunc
    return func
print superfunc(1)(2)(3)

你忘记了第二个函数的返回。这是固定函数

def superfunct(x):
  def func(y):
    def subfunc(z):
      return x + y + z
    return subfunc
  return func
print superfunct(1)(2)(3)

相关内容

最新更新