如何将装饰器应用于lambda? [英] How to apply decorators to lambdas?

查看:81
本文介绍了如何将装饰器应用于lambda?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Python中的lambda函数上使用装饰器是否有语法?示例:

Is there any syntax for using a decorator on a lambda function in Python? Example:

def simpledecorator(f):
     def new_f():
         print "Using a decorator: "
         f()
     return  new_f

@simpledecorator
def hello():
    print "Hello world!"

输出结果:

>>> hello()
Using a simple decorator:
Hello world!

但是当我尝试使用lambda进行相同操作时:

Yet when I try the same with a lambda:

@anotherdecorator
f = lambda x: x * 2

我明白了:

  File "<stdin", line 2
    f = lambda x: x * 2
    ^
 SyntaxError: invalid syntax



<我觉得这可能是通过允许将语句插入 lambda使其更通用的好方法。但是,如果存在这样的功能,我不知道语法是什么。

I feel like this might be a good way to make lambdas more versatile by allowing statements to be "injected" into them. But if there exists such a feature, I don't know what the syntax is.

推荐答案

f = anotherdecorator(lambda x: x * 2)

这篇关于如何将装饰器应用于lambda?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆