装饰器可以在运行时使用lambda表达式吗?

use*_*514 12 python lambda decorator

def attrs(**kwds):
      def decorate(f):
          for k in kwds:
              setattr(f, k, kwds[k])
          return f
      return decorate

@attrs(argument_types=(int, int,), returns=int)
def add(a, b):
      return a + b 
Run Code Online (Sandbox Code Playgroud)

这里我需要add()可以显示其可接受的参数类型.但是我可以在运行时做这样的事吗?

ladd=[]
for x in range(0,10):

      @attrs(argument_types=int, returns=int,default_parameter1 = x) 
      exp =  lambda : add(a,x)  
      ladd.append(exp)
Run Code Online (Sandbox Code Playgroud)

要么

ladd=[]
for x in range(0,10):

      @attrs(argument_types=int, returns=int,default_parameter1 = x) 
      addx = functools.partial(add, 2)  
      ladd.append(addx)
Run Code Online (Sandbox Code Playgroud)

我需要那些函数可以使用"decoratored"参数绑定生成运行时


好吧,这里是错误信息,我认为上面的代码无法正常工作,但我从未尝试将其粘贴到python来测试它...

>>> ladd=[]
>>> for x in range(0,10):
...     @attrs(argument_types=int, returns=int,default_parameter1 = x) 
...     exp =  lambda : add(a,x)  
  File "<stdin>", line 3
    exp =  lambda : add(a,x)  
      ^
SyntaxError: invalid syntax
>>>     ladd.append(exp)
  File "<stdin>", line 1
    ladd.append(exp)
    ^
IndentationError: unexpected indent
>>> 
Run Code Online (Sandbox Code Playgroud)

小智 10

装饰器语法只是语法糖,虽然它将人们的想法引导到有趣的方向.

@expr
def f(...):
    ...
Run Code Online (Sandbox Code Playgroud)

是完全相同的

def f(...):
    ...
f = expr(f)
Run Code Online (Sandbox Code Playgroud)

所以你可以使用attrs(argument_types=..., ...)(lambda: ...).


Joc*_*zel 8

@语法仅仅是调用与它的参数一个函数的装饰语法糖.这意味着

@deco
def func(): pass
Run Code Online (Sandbox Code Playgroud)

是相同的

def func(): pass
func = deco(func)
Run Code Online (Sandbox Code Playgroud)

所以你想要的只是:

ladd=[]

for x in range(0,10):    
      deco = attrs(argument_types=int, returns=int,default_parameter1 = x) 
      addx = functools.partial(add, 2)
      # append the "decorated" function
      ladd.append(deco(addx))
Run Code Online (Sandbox Code Playgroud)