ddd*_*ddd 4 python function decorator args
我想用Python编写一个函数.给定一个函数,返回一个新函数,该函数向后运行带有参数的原始函数.例如,输入函数func是pow,所以func(2,3)= 8.返回的新函数将执行pow(3,2)= 9.
我在另一篇文章中找到了此解决方案
def flip(func):
'Create a new function from the original with the arguments reversed'
@wraps(func)
def newfunc(*args):
return func(*args[::-1])
return newfunc
Run Code Online (Sandbox Code Playgroud)
有没有办法没有@wrap?参数的数量是未知的.它可以是任何类型:int, string. 所以我想要的函数只接受一个参数,它是原始函数的名称.
reverse_args(f)
Run Code Online (Sandbox Code Playgroud)
在调用时,*args将遵循:
reverse_args(func)(*args)
Run Code Online (Sandbox Code Playgroud)
如果这是你唯一的疑问:@wraps不需要装饰器.它的作用是向它标记的包装函数添加一些元数据,以使其更接近它所包含的原始函数.例如,它会覆盖包装器(在这种情况下newfunc)__name__属性,使其看起来与原始的相同(如果打印)或者如果repr看到它.
反转参数序列的是args[::-1]部分,以及*运算符,它将参数分配回去.