python 装饰器执行顺序
本文介绍了python 装饰器执行顺序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
问 题
#!/usr/bin/python**加粗文字**
def deco_functionNeedDoc(func):
if func.__doc__ == None:
print func,"has no __doc__, it's a bad habit."
else:
print func,':',func.__doc__,'.'
return func
@deco_functionNeedDoc
def f():
print 'f() Do something'
@deco_functionNeedDoc
def g():
'I have a __doc__'
print 'g() Do something'
f()
g()
Actual Result:
<function f at 0x7f31e65d05f0> has no __doc__, it's a bad habit.
<function g at 0x7f31e65d0668> : I have a doc .
f() Do something
g() Do something
Expected Result:
<function f at 0x7f31e65d05f0> has no __doc__, it's a bad habit.
f() Do something
<function g at 0x7f31e65d0668> : I have a doc .
g() Do something
f()和g()被修饰后是如何执行的?
另外一段使用装饰器的代码
#-*- coding: UTF-8 -*-
import time
def timeit(func):
def wrapper():
start = time.clock()
func()
end =time.clock()
print 'used:', end - start
return wrapper
@timeit
def foo():
print 'in foo()'
foo()
Actual Result:
in foo()
used: 2.1e-05
这一段使用wrapper方法执行时先执行foo(),再执行wrapper()。
加了wrapper会有什么差别吗?
解决方案
装饰器更像是编译时所执行的程序,即使在原函数还未装载入内存前就先为函数进行装饰工作,所以这里是先进行装饰,再运行的装饰后的函数。不然,你试试在最后不执行f()、g()同样可以执行装饰函数里面的代码
这篇关于python 装饰器执行顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文