我有许多可重用的函数,都具有相同的签名(它们采用 arecord
并返回 a float
)。我经常需要将函数组合成一个新函数。
假设我想创建一个接受 a 的函数record
,应用于f
它,如果结果为负,则将其转换为零。我有两种方法:组合和功能修改。每种方法的优缺点是什么?
作品:
def non_negative(value):
return max(0, value)
g = compose(non_negative, f)
# from functional module by Collin Winter
def compose(func_1, func_2, unpack=False):
"""
compose(func_1, func_2, unpack=False) -> function
The function returned by compose is a composition of func_1 and func_2.
That is, compose(func_1, func_2)(5) == func_1(func_2(5))
"""
if not callable(func_1):
raise TypeError("First argument to compose must be callable")
if not callable(func_2):
raise TypeError("Second argument to compose must be callable")
if unpack:
def composition(*args, **kwargs):
return func_1(*func_2(*args, **kwargs))
else:
def composition(*args, **kwargs):
return func_1(func_2(*args, **kwargs))
return composition
修改:
def non_negative(func):
def new_func(record):
return max(0, func(record))
return new_func
g = non_negative(f)