这样我们基本可以是实现对 a 和 b 的不同操作。但是这个方法的通用性不强,因为fun 函数可能还有其他需要传入的参数,而这个参数不在 run 函数内,比如我们在 multiply 函数内将乘积结果打印出来,那就需要用到 *args 和 **kwargs ,他俩分别代表任意参数和任意关键字参数。对上面的代码进行改进后如下:
到这里,我们发现 dec 函数返回的 run 函数传参数很不方便,如果在 dec 函数中传*args 和**kwargs 那就和前面飞雷神标记的 run 函数没有区别了,所以我们可以在 dec 函数中不直接返回 run 函数的返回值,而是返回 run 函数本身,然后在外部调用 run(*args,**kwargs) 得到 run 函数的返回值。
defmultiply(a,b,show=False):if show:print(a*b)return a*b
defdec(fun):defrun(*args,**kwargs):
a=int(input('please input a'))
b=int(input('please input b'))
ret=fun(a,b,*args,**kwargs)return ret
return run
mul_run=dec(multiply)# dec_fun1
ret=mul_run(show=True)# dec_fun2
如上,由于在定义 run 函数时 fun 函数传入的是 multiply 函数,所以 mul_run 就是 fun 函数为 multiply 的 run 函数了,此时只要运行 mul_run 函数并传入参数即可得到返回值。此时,dec 函数就是装饰函数,我们在 multiply 函数上方添加 @dec 后,后面直接执行 multiply 函数,等价于执行上面 dec_fun1 和 dec_fun2 。
defdec(fun):defrun(*args,**kwargs):
a=int(input('please input a'))
b=int(input('please input b'))
ret=fun(a,b,*args,**kwargs)return ret
return run
@ dec
defmultiply(a,b,show=False):if show:print(a*b)return a*b
ret=multiply(show=True)