Python深层嵌套工厂函数

Python深层嵌套工厂函数,python,function,factory,Python,Function,Factory,在“学习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) <functi

在“学习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制造商(N):
def行动(X):
返回X**N
返回动作
>>>制造商(2)
>>>o=制造商(2)
>>>o(3)
8.
>>>制造商(2)
>>>制造商(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)
>>>
def超级函数(X): ... def func(Y): ... def子功能(Z): ... 返回X+Y+Z ... 返回函数 ... >>>超级基金() 回溯(最近一次呼叫最后一次): 文件“”,第1行,在 TypeError:superfunc()正好接受1个参数(给定0) >>>超级基金(1) >>>超级基金(1)(2) >>>超级基金(1)(2)(3) 回溯(最近一次呼叫最后一次): 文件“”,第1行,在 TypeError:“非类型”对象不可调用 >>>超级基金(1)(2) >>> 为什么
superfunc(1)(2)(3)
不工作,而
maker(2)(3)
工作


虽然这种嵌套在我看来显然不是一个好的、可用的代码,但Python仍然认为它是有效的,所以我很好奇如何调用它。

您会得到一个
TypeError
,因为function
func
不返回任何东西(因此它的返回是
NoneType
)。它应该返回subfunc:

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

您的
superfunc
中缺少一个返回:您有一个
return
用于
subfunc
,但没有一个用于
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)

如果只缩进4个空格而不是8个空格,看起来会更好。
superfunc(1)(2)
返回None,然后调用(3),即None(3),这会引发错误。事实上,忘记return语句是令人尴尬的:)我应该通过None来猜测函数默认返回的值。