1.什么是decorator?
装饰器就是,装饰你目标的东西。其实wapper来理解更好~就好比钢铁侠的盔甲!
def decorator(fun):
def warrper(name):
start = time.time()
fun(name)
runtime = time.time() - start
print runtime
return warrper
@decorator
def do_something(name):
for i in range(10000000):
pass
print 'name:',name
if __name__ == '__main__':
do_something('Li yun long')
name: Li yun long
0.27599978447
让参数不固定:
def decorator(fun):
def wapper(*args,**kwargs):
start = time.time()
fun(*args,**kwargs)
runtime = time.time() - start
print runtime
return wapper
@decorator
def do_something(user,name):
for i in range(10000000):
pass
print "user:",user
print "name:",name
if __name__ == '__main__':
do_something('Li yun long','yun long')
user: Li yun long
name: yun long
0.30999994278
改装一下,让它带参数,
···
def decorator(num):
def _decorator(fun):
def wapper(args,kwargs):
start = time.time()
for i in xrange(num):
fun(args,**kwargs)
runtime = time.time() - start
print runtime
return wapper
return _decorator
@decorator(2)
def do_something(user,name):
for i in range(10000000):
pass
print "user:",user
print "name:",name
if name == 'main':
do_something('Li yun long','yun long')
···
user: Li yun long
name: yun long
user: Li yun long
name: yun long
0.5
不要试图在里面些两个,第二个不会运行的.
那么,调用顺序呢?
def decorator(fun):
print "decorator"
def warrper():
print "wapper"
start = time.time()
fun()
runtime = time.time() - start
print runtime
return warrper
@decorator
def do_something():
for i in range(10000000):
pass
print 'do_something'
它的结果是:
被装饰器装饰过的函数名:
def decorator(fun):
#print "decorator"
def warrper(name):
#print "wapper"
start = time.time()
fun(name)
runtime = time.time() - start
print runtime
return warrper
@decorator
def do_something(name):
for i in range(10000000):
pass
print 'do_something',name
if __name__ == '__main__':
print do_something.__name__
用functools:
import functools
def decorator(fun):
@functools.wraps(fun)
def warrper(name):
start = time.time()
fun(name)
runtime = time.time() - start
print runtime
return warrper
@decorator
def do_something(name):
for i in range(10000000):
pass
print 'do_something',name
if __name__ == '__main__':
print do_something.__name__