如何添加函数
我到处查找,但这个话题很难搜索,信息太杂了。我想做的事情是这样的:
def f(arg):
return arg * arg
def add(self, other):
return self * other
f.__add__ = add
cubefunction = f + f
但是在给cubefunction赋值的时候,我遇到了错误,比如:
TypeError: unsupported operand type(s) for +: 'function' and 'function'
在Python中难道就不能进行函数代数吗?还是我只是犯了个低级错误?
补充:很久之后,我在阅读Python官方的函数式编程入门时(http://docs.python.org/howto/functional.html),在最后提到了一个第三方包“functional”(http://oakwinter.com/code/functional/documentation/),这个包可以组合函数,也就是说:
>>> from functional import compose
>>> def add(a, b):
... return a + b
...
>>> def double(a):
... return 2 * a
...
>>> compose(double, add)(5, 6)
22
5 个回答
1
我想你想要做的是:
cubefunction = (lambda x: add(f(x), f(x)))
1
在你的代码中,f需要是一个类,而不是一个函数。如果你有一个类,你可以实现一个add(self, other)的方法,这样就可以重载+这个运算符了。
6
我觉得你可能做不到这个。不过,使用 __call__
这个特殊的方法,你可以定义一个自己的可调用类,这个类就像一个函数一样,并且你可以在这个类上定义 __add__
方法:
>>> 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
在这里,+
被重载为逐点相加,而 *
被重载为组合。当然,你可以做任何你想做的事情。
对于Python高手来说,这是个有趣的问题:为什么下面的代码不工作(虽然这是一种不太干净的黑科技)?
>>> 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'