2

通过“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 仍然认为它是有效的,所以我很好奇如何调用它。

4

4 回答 4

4

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

>>> def superfunc(X):
...     def func(Y):
...             def subfunc(Z):
...                     return X + Y + Z
...             return subfunc
...     return func
... 
于 2012-10-02T08:59:05.750 回答
2

superfunc 更正,带有调用示例

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

print superfunc(1)(2)(3)
于 2012-10-02T09:01:44.593 回答
2

您的某处缺少返回superfunc:您有returnfor subfunc,但没有 for func

于 2012-10-02T08:59:41.927 回答
1

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

def superfunct(x):
  def func(y):
    def subfunc(z):
      return x + y + z
    return subfunc
  return func

print superfunct(1)(2)(3)
于 2012-10-02T09:03:18.593 回答