python,困惑在装饰和闭合 [英] python, confused in decorate and closure
问题描述
我有一些测试代码:
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不是已定义的错误
when run this code, I got an error shows that 'inputed_num' is not defined
我的问题是:
在wrap函数中,有没有一个闭包func可以得到'inputed_num'?
My question is: In wrap function, is there not a closure that func can got 'inputed_num' ?
无论如何,如果没有,我应该如何做到我的目标:初始化一些值,并直接在主函数中使用这个值。
Anyway, If not, how should I do to got my aim: Initialize some value, and use this value directly in the main function.
思考。
推荐答案
我的问题是:在wrap函数中,有没有一个闭包,func可以得到'inputed_num'?
My question is: In wrap function, is there not a closure that func can got 'inputed_num' ?
对不起,这不是装饰器工作的方式。在之后,函数被初始定义后应用。
Sorry, that's not the way decorators work. They get applied after the function is initially defined. By then, it's too late.
写下:
@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成为 test 的第一个参数。然后,让装饰器传递参数:
To achieve your goal, let inputed_num be the first argument to test. Then, have your decorator pass in that argument:
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
希望为您清除一切: - )
Hope that clears everything up for you :-)
这篇关于python,困惑在装饰和闭合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!