<p>我觉得你做不到。但是,使用<code>__call__</code>magic方法可以定义自己的可调用类,该类充当函数,并且您可以在其上定义<code>__add__</code>:</p>
<pre><code>>>> class FunctionalFunction(object):
... def __init__(self, func):
... self.func = func
...
... def __call__(self, *args, **kwargs):
... return self.func(*args, **kwargs)
...
... def __add__(self, other):
... def summed(*args, **kwargs):
... return self(*args, **kwargs) + other(*args, **kwargs)
... return summed
...
... def __mul__(self, other):
... def composed(*args, **kwargs):
... return self(other(*args, **kwargs))
... return composed
...
>>> triple = FunctionalFunction(lambda x: 3 * x)
>>> times_six = triple + triple
>>> times_six(2)
12
>>> times_nine = triple * triple
>>> times_nine(3)
27
</code></pre>
<p>这里<code>+</code>重载为逐点加法,而<code>*</code>重载为复合。当然,你可以做任何你喜欢的事。</p>
<hr/>
<p>对于Python专家来说,一个有趣的问题是:为什么下面的代码不起作用(尽管它是肮脏的hack)?</p>
<pre><code>>>> from types import MethodType, FunctionType
>>> f = lambda: None
>>> f.__add__ = MethodType(lambda self, other: "summed!", f, FunctionType)
>>> f.__add__(f)
'summed!'
>>> f + f
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for +: 'function' and 'function'
</code></pre>