Raf*_*ler 21 python syntax lambda decorator
是否有任何语法在Python中的lambda函数上使用装饰器?例:
def simpledecorator(f):
def new_f():
print "Using a decorator: "
f()
return new_f
@simpledecorator
def hello():
print "Hello world!"
Run Code Online (Sandbox Code Playgroud)
结果输出:
>>> hello()
Using a simple decorator:
Hello world!
Run Code Online (Sandbox Code Playgroud)
然而,当我尝试使用lambda时:
@anotherdecorator
f = lambda x: x * 2
Run Code Online (Sandbox Code Playgroud)
我明白了:
File "<stdin", line 2
f = lambda x: x * 2
^
SyntaxError: invalid syntax
Run Code Online (Sandbox Code Playgroud)
我觉得这可能是一个很好的方法,通过允许语句"注入"它们使lambdas更加通用.但如果存在这样的功能,我不知道语法是什么.
dan*_*n04 39
f = anotherdecorator(lambda x: x * 2)
Run Code Online (Sandbox Code Playgroud)