装饰器
Posted wrw202
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了装饰器相关的知识,希望对你有一定的参考价值。
1.高阶函数定义
a.函数接收的参数是一个函数名
def foo():
time.sleep(2)
print(‘hello‘)
def test(func):
print(func)
start_time=time.time()
func()
stop_time=time.time()
print(‘running %s‘% (stop_time-start_time))
test(foo)
b.不改变函数的调用方式
def foo():
print(‘from the foo‘)
def test(func):
return func
foo=test(foo)
foo()
c.闭包
def father(name):
# print(‘from father %s‘% name)
def son():
# name=‘kevin_1‘
print(‘my father is %s‘% name)
def grandson():
print(‘my yeye is %s‘ % name)
grandson()
# print(locals())
son()
father(‘kevin‘)
装饰器
def timmer(func): #func=test
def wrapper():
start_time=time.time()
func() #test()
stop_time=time.time()
print(‘runing time %s‘ %(stop_time-start_time))
return wrapper
def test():
time.sleep(2)
print(‘running‘)
test=timmer(test) #test=wrapper
test() #wrapper()
装饰器return test
def timmer(func): #func=test
def wrapper():
start_time=time.time()
res=func() #test()
stop_time=time.time()
print(‘runing time %s‘ %(stop_time-start_time))
return res
return wrapper
@timmer #test=timmer(test) test=wrapper
def test():
time.sleep(2)
print(‘running‘)
# test() #wrapper()
res=test() #test
print(res)
函数加参数
def timmer(func):
def wrapper(*args,**kwargs):
start_time=time.time()
res=func(*args,**kwargs)
stop_time=time.time()
return res
return wrapper
@timmer
def func(*args,**kwargs):
time.sleep(2)
print(‘%s,%s‘%(args,kwargs))
return 1234
func(‘kevin‘,19,age=19)
以上是关于装饰器的主要内容,如果未能解决你的问题,请参考以下文章