私は、すべて同じ署名を持つ再利用可能な関数を多数持っています (それらは a を取り、 arecordを返しますfloat)。関数を新しい関数に結合する必要があることがよくあります。
recordを受け取り、それに適用fし、結果が負の場合はそれをゼロに変換する関数を作成したいとしましょう。それを行うには、構成と関数の変更の 2 つの方法があります。各アプローチの長所と短所は何ですか?
構成:
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)