如何使用后退参数返回新函数

时间:2018-09-26 19:02:09

标签: python function decorator args

我想用Python编写一个函数。给定一个函数,返回一个新函数,该函数将向后运行带有参数的原始函数。 例如,输入函数funcpow,因此func(2,3)=8。返回的新函数将做pow(3,2)= 9。

我在另一个post

中找到了此解决方案
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

没有@wrap可以做到吗?参数的数量未知。并且可以是任何类型:intstring。因此,我想要的函数只接受一个参数,即原始函数的名称。

reverse_args(f)

被调用时,* args将跟随:

reverse_args(func)(*args)

2 个答案:

答案 0 :(得分:5)

如果这是您唯一的疑问:不需要@wraps装饰器。 它所做的是在标记的包装函数中添加一些元数据,以使其与包装的原始函数更加相似。例如,它会覆盖包装器(在这种情况下为newfunc)的__name__属性,使其在打印时或看到其repr时看起来与原始属性相同。

与参数顺序相反的是args[::-1]部分和*运算符,该运算符将参数分配回去。

答案 1 :(得分:3)

带有public class Generator { public static void main (String[] args) { String input = JOptionPane.showInputDialog("Enter Desired Analysis level"); int analysisLevel = Integer.parseInt(input); try { if (analysisLevel >= 0) { System.out.println(analysisLevel); } else { input = JOptionPane.showInputDialog("Enter Desired Analysis level"); } } catch (Exception e) { System.out.println("Input was no number" + e); System.exit(0); } System.exit(0); } } 吗?

lambda

打印def f(a,b): return a**b def transform(f): return lambda *args : f(*args[::-1]) g=transform(f) print(g(4,5))