Python_装饰器
1.装饰器的本质:函数
2.装饰器的功能:为其他函数添加附加功能(装饰其他函数)
3.装饰器的原则:不能修改被装饰函数的 a.源代码;b.调用方式(装饰器对原函数透明)
装饰器实例:
# -*- coding:utf-8 -*-
# Author:Soap
import time
def timer(flag):#装饰器判断层
def wapper(func):#装饰器函数接受层
def deco(*args,**kwargs):#装饰器函数体
start_time = time.time()
res = func(*args,**kwargs) #test1 执行
stop_time = time.time()
if flag == 'start time':
print('the start time is %s'%(start_time))
elif flag == 'stop time':
print('the stop time is %s' % (stop_time))
return res
return deco
return wapper
@timer('start time')
def test1(name):
time.sleep(1)
print('in the test1: ',name)
return 0
@timer('stop time')
def test2(name):
time.sleep(1)
print('in the test2: ', name)
return 0
print(test1('soap'))
print(test2('soap'))

浙公网安备 33010602011771号