如何添加函数

2024-05-23 17:38:07 发布

您现在位置:Python中文网/ 问答频道 /正文

我到处都找过了,但如果没有太多的噪音,这是一个很难找到的话题。我想这样做:

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

Tags: 函数composeselfaddhttpreturndef错误
3条回答

我想你的意思是:

cubefunction = (lambda x: add(f(x), f(x)))

我觉得你做不到。但是,使用__call__magic方法可以定义自己的可调用类,该类充当函数,并且您可以在其上定义__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专家来说,一个有趣的问题是:为什么下面的代码不起作用(尽管它是肮脏的hack)?

>>> 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'

在您的代码中,f需要是一个类,而不是一个函数。如果您有一个类,则可以实现一个将重载+运算符的add(self,other)方法。

相关问题 更多 >