Python深厚的嵌套工厂功能 [英] Python deep nesting factory functions
本文介绍了Python深厚的嵌套工厂功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
$ $ $ $ $ $ $ $ $ $ def $($)$ def $ X ** N
退货操作
>>>制造商(2)
<在0x7f9087f008c0处的功能动作>
>>> o = maker(2)
>>> o(3)
8
>>>制造商(2)
< 0x7f9087f00230的功能动作>
>>>制造商(2)(3)
8
但是,想法如何称呼它:
>>> def superfunc(X):
... def func(Y):
... def subfunc(Z):
... return X + Y + Z
。 .. return func
...
>>> superfunc()
Traceback(最近一次调用最后一次):
在< module>中,第1行的文件< stdin>
TypeError:superfunc()只需要1个参数(0给出)
>>> superfunc(1)
>>> superfunc(1)(2)
>>>
Traceback(最近一次调用最后一次):
在< module>中,第1行的文件< stdin>
TypeError:'NoneType'对象不可调用
>>> superfunc(1)(2)
>>>
为什么不是 superfunc(1)(2)(3)
work while 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
...
Working through "Learning Python" came across factory function. This textbook example works:
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
However when going deeper another level I have no idea how to call it:
>>> 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)
>>>
Why doesn't superfunc(1)(2)(3)
work while maker(2)(3)
does?
While this kind of nesting certainly doesn't look like a good, usable code to me, Python still accepts it as valid, so I'm curious as to how this can be called.
解决方案
You get a TypeError
because function func
doesn't return anything (thus its return is NoneType
). It should return subfunc
:
>>> def superfunc(X):
... def func(Y):
... def subfunc(Z):
... return X + Y + Z
... return subfunc
... return func
...
这篇关于Python深厚的嵌套工厂功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文