【发布时间】:2019-06-06 18:56:36
【问题描述】:
编写一个由其他两个函数组成的函数相当简单。 (为简单起见,假设它们都是一个参数。)
def compose(f, g):
fg = lambda x: f(g(x))
return fg
def add1(x):
return x + 1
def add2(x):
return x + 2
print(compose(add1, add2)(5)) # => 8
我想使用运算符进行合成,例如,(add1 . add2)(5)。
有没有办法做到这一点?
我尝试了各种装饰器配方,但都无法使用。
def composable(f):
"""
Nothing I tried worked. I won't clutter up the question
with my failed attempts.
"""
@composable
def add1(x):
return x + 1
【问题讨论】:
-
您的意思是要使用中缀运算符而不是标准的前缀调用表示法?
-
相关的,可能是骗人的:How to multiply functions in python?
标签: python-3.x python-decorators function-composition