我有一些测试代码:
def num(num): def deco(func): def wrap(*args, **kwargs): inputed_num = num return func(*args, **kwargs) return wrap return deco @num(5) def test(a): return a + inputed_num print test(1)
运行此代码时,我得到一个错误,表明未定义’inputed_num’
我的问题是:
在wrap函数中,是否有一个闭包,func可以得到’inputed_num’?
无论如何,如果没有,我该如何实现我的目标:初始化一些值,并在main函数中直接使用该值.
想.
解决方法:
My question is: In wrap function, is there not a closure that func can got ‘inputed_num’ ?
对不起,这不是装饰工作的方式.它们在最初定义函数后应用.到那时,为时已晚.
当你写:
@num(5) def test(a): return a + inputed_num
这相当于:
def test(a): return a + inputed_num test = num(5)(test) # note that num(5) is called after test() is defined.
为了实现您的目标,让inputed_num成为第一个要测试的参数.然后,让装饰器传入该参数:
def num(num): def deco(func): def wrap(*args, **kwargs): inputed_num = num return func(inputed_num, *args, **kwargs) # this line changed return wrap return deco @num(5) def test(inputed_num, a): # this line changed return a + inputed_num @num(6) def test2(inputed_num, a): return a + inputed_num print test(10) # outputs 15 print test2(10) # outputs 16
希望为你清除一切:-)