本文研究的主要内容是Python中装饰器相关学习总结,具体如下。
from time import ctime, sleepdef timefun(func): def wrappedfunc(): print("%s called at %s"%(func.__name__, ctime())) func() return wrappedfunc@timefundef foo(): print("I am foo")foo()sleep(2)foo()
分析如下:
上面代码理解装饰器执行行为可理解成
foo = timefun(foo)
1,foo先作为参数赋值给func后,foo接收指向timefun返回的wrappedfunc
2,调用foo(),即等价调用wrappedfunc()
3,内部函数wrappedfunc被引用,所以外部函数的func变量(自由变量)并没有释放
4,func里保存的是原foo函数对象
例2:被装饰的函数有参数
from time import ctime, sleepdef timefun(func): def wrappedfunc(a, b): print("%s called at %s"%(func.__name__, ctime())) print(a, b) func(a, b) return wrappedfunc@timefundef foo(a, b): print(a+b)foo(3,5)sleep(2)foo(2,4)
例3:被装饰的函数有不定长参数
from time import ctime, sleepdef timefun(func): def wrappedfunc(*args, **kwargs): print("%s called at %s"%(func.__name__, ctime())) func(*args, **kwargs) return wrappedfunc@timefundef foo(a, b, c): print(a+b+c)foo(3,5,7)sleep(2)foo(2,4,9)
例4:装饰器中的return
from time import ctime, sleepdef timefun(func): def wrappedfunc(): print("%s called at %s"%(func.__name__, ctime())) func() return wrappedfunc@timefundef foo(): print("I am foo")@timefundef getInfo(): return '----hahah---'foo()sleep(2)foo()print(getInfo())
执行结果:
foo called at Sun Jun 18 00:31:53 2017
I am foo
foo called at Sun Jun 18 00:31:55 2017
I am foo
getInfo called at Sun Jun 18 00:31:55 2017
None如果修改装饰器为return func(),则运行结果:
foo called at Sun Jun 18 00:34:12 2017
I am foo
foo called at Sun Jun 18 00:34:14 2017
I am foo
getInfo called at Sun Jun 18 00:34:14 2017
----hahah---
小结:一般情况下为了让装饰器更通用,可以有return
例5:装饰器带参数,在原有装饰器的基础上,设置外部变量
from time import ctime, sleepdef timefun_arg(pre="hello"): def timefun(func): def wrappedfunc(): print("%s called at %s %s"%(func.__name__, ctime(), pre)) return func() return wrappedfunc return timefun@timefun_arg("itcast")def foo(): print("I am foo")@timefun_arg("python")def too(): print("I am too")foo()sleep(2)foo()too()sleep(2)too()可以理解为foo()==timefun_arg("itcast")(foo)()
新闻热点
疑难解答