如何添加功能

use*_*904 8 python functional-programming operators

我看了很多,但搜索没有很多噪音是一个难题.我想做这样的事情:

def f(arg):
  return arg * arg

def add(self, other):
  return self * other

f.__add__ = add

cubefunction = f + f
Run Code Online (Sandbox Code Playgroud)

但是我在对cubeto的赋值上遇到错误,例如:

TypeError: unsupported operand type(s) for +: 'function' and 'function'
Run Code Online (Sandbox Code Playgroud)

在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
Run Code Online (Sandbox Code Playgroud)

Kat*_*iel 6

我认为你不能做到这一点.但是,使用__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
Run Code Online (Sandbox Code Playgroud)

+是重载到逐点添加和*组合.当然,你可以做任何你喜欢的事情.


对于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'
Run Code Online (Sandbox Code Playgroud)