import time
def logger(func):
def wrapper(*args,**kw):
print('我准备开始计算;{} 函数了:'.format(func.__name__))
func(*args,**kw)
print('啊哈,我计算完啦。给自己加个鸡腿!!')
return wrapper
@logger
def add(x,y):
print('{} + {} = {}'.format(x, y, x+y))
add(x= 200,y =50)
def timer(func):
def wrapper(*args,**kw):
t1 = time.time()
func(*args,**kw)
t2 =time.time()
cost_time =t2-t1
print("花费时间:{}秒".format(cost_time))
return wrapper
@timer
def want_sleep(sleep_time):
time.sleep(sleep_time)
want_sleep(10)
def say_hello(contry):
def wrapper(func):
def deco(*args,**kw):
if contry =='china':
print("你好")
elif contry == "american":
print('hello .')
else:
return
func(*args,**kw)
return deco
return wrapper
@say_hello('american')
def american():
print("I am from American")
@say_hello('china')
def chinese():
print("我来自中国")
american()
print('-----------')
chinese()
最近因为在某公众号上看到装饰器用于测试异常处理,所以就学习了一下装饰器