#无传参版
import time
def timer(func):# 函数test当做了一个变量传给了func
def conut():
start_time=time.time()
func()
stop_time=time.time()
print('the func run time is %s'%(stop_time-start_time))
return conut
# @timer # 相当于test=timer(test)
def test():
time.sleep(3)
print('in the test')
test=timer(test)
test()
#有传参版
import time
def timer(func):# 函数test当做了一个变量传给了func
def conut(*args,**kwargs):
start_time=time.time()
func(*args,**kwargs)
stop_time=time.time()
print('the func run time is %s'%(stop_time-start_time))
return conut
@timer # 相当于test=timer(test)
def test(name,age):
time.sleep(3)
print('%s is %s'%(name,age))
# test=timer(test)
test('bruce',22)
#高级版
import time
name,password='bruce','123456'
def auth(auth_type):
def out_wrapper(func):
def wrapper(*args,**kwargs):
if auth_type == 'local':
username=input('User:').strip()
passwd=input('Passwd:').strip()
if username == name and passwd == password:
print('\033[32;1m认证成功!\033[32;0m')
ret = func(*args,**kwargs)
return ret
else:
exit()
elif auth_type == 'ldap':
print('不会!')
return wrapper
return out_wrapper
@auth(auth_type='ldap')
def index():
print('welcom to index page')
@auth(auth_type='local')
def home():
print('welcom to home page')
return home
index()
home()
"""
装饰器定式
"""
def wrapper(f):
def inner(*args,**kwargs):
"""在被装饰函数之前要做的事"""
ret = f(*args,**kwargs)
"""在被装饰函数之后要做的事"""
return ret
return inner
@wrapper
def func(a,b):
time.sleep(2)
print("hello 大家好!",a,b)
return "新年好"
print(func(1,2))