In [107]: f = abs
In [108]: f(-10)
Out[108]: 10
In [109]: dir(f)
Out[109]:
['__call__',
'__class__',
'__delattr__',
'__dir__',
...]
上例中的f对象指向了abs类型,由于f对象中有__call__方法,因此f(-10)实现了对abs(-10)的重载。
In [134]: %cpaste
Pasting code; enter '--' alone on the line to stop or use Ctrl-D.
:
:def lazy_sum(*args):
: def sum():
: ax = 0
: for n in args:
: ax = ax + n
: return ax
: return sum
:--
In [135]: f = lazy_sum(1,3,5,7,9)
In [136]: f
Out[136]: <function __main__.lazy_sum.<locals>.sum>
In [137]: f()
Out[137]: 25
为什么返回函数能够这么神奇,咱们一探究竟。