【问题标题】:Python - decorator function using lambda function for a classPython - 对类使用 lambda 函数的装饰器函数
【发布时间】:2020-02-29 15:24:17
【问题描述】:

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

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 函数时,它会自动理解它是它想要作为输入的装饰函数吗?

非常感谢!

【问题讨论】:

    标签: python oop lambda decorator


    【解决方案1】:

    严格来说,pipeline_step 不是装饰者;它返回一个装饰器,它是将被装饰的函数作为参数的函数。

    pipeline_step 也可以使用def 语句编写,这样可以使其更加明确:

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

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

    使用 lambda 表达式只是跳过了必须为装饰器命名的步骤,它永远不会在 pipeline_step 本身之外可见或使用。


    为了完整起见,提醒一下

    @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)
    

    【讨论】:

    • 感谢编辑,让我更好地理解。我也可以这样做:pipeline_step(step_id='lacocoracha')(my_sum)(12)
    猜你喜欢
    • 2013-01-25
    • 1970-01-01
    • 2014-07-21
    • 1970-01-01
    • 1970-01-01
    • 2019-12-18
    • 2020-07-13
    • 1970-01-01
    • 2011-10-04
    相关资源
    最近更新 更多