Python-为类使用lambda函数的decorator函数

Python-为类使用lambda函数的decorator函数,python,oop,lambda,decorator,Python,Oop,Lambda,Decorator,我在线检查了一些关于如何跟踪特定管道步骤的代码,得到了以下代码: class Pipeline(): def __init__(self, step_id, fct_to_call): self.step_id = step_id self.fct_to_call = fct_to_call def __call__(self, *args): return self.fct_to_call(*args) def pipelin

我在线检查了一些关于如何跟踪特定管道步骤的代码,得到了以下代码:

class Pipeline():
    def __init__(self, step_id, fct_to_call):
        self.step_id = step_id
        self.fct_to_call = fct_to_call

    def __call__(self, *args):
        return self.fct_to_call(*args)

def pipeline_step(step_id):
    return lambda f: Pipeline(step_id=step_id, fct_to_call=f)

@pipeline_step(step_id='lacocouracha')
def my_sum(numba):
    output = numba *1.45
    return output

a = my_sum(12)
我的问题与何时使用lambda函数有关。在调试器模式下运行时,我看到lambda函数“f”指的是“my_sum”。所以当在装饰函数中使用lambda函数时,它会自动理解它是作为输入的装饰函数

非常感谢

严格地说,管道步骤不是装饰者;它返回一个decorator,该函数将被修饰的函数作为参数

pipeline_步骤也可以使用def语句编写,这可以使其更加明确:

def pipeline_step(step_id):
    def decorator(f):
        return Pipeline(step_id=step_id, fct_to_call=f)
    return decorator
调用pipeline_stepstep_id='lacocouracha'时,它将返回一个新的函数decorator,该函数充当变量step_id的闭包。decorator然后接收函数my_sum作为其参数,并且名称my_sum将反弹到decorator返回的pipeline实例

使用lambda表达式只需跳过必须为装饰器命名的步骤,而装饰器的名称在pipeline_步骤之外永远不会可见或使用

为完整起见,提醒您:

@pipeline_step(step_id='lacocouracha')
def my_sum(numba):
    output = numba *1.45
    return output
语法上的糖是什么

def my_sum(numba):
    output = numba *1.45
    return output

my_sum = pipeline_step(step_id='lacocoracha')(my_sum)
# == (lambda f: Pipeline(step_id=step_id, fct_to_call=f))(my_sum)
# == Pipeline(step_id=step_id, fct_to_call=my_sum)

谢谢你的编辑,让我更好地理解。我也可以这样做:管道步骤12