装饰器wapper函数可以使用fun的参数,并且可以给fun传递不一样的参数
def deco(func): def wrapper(a, b): print(a) startTime = time.time() c = a + 1 func(c, b) endTime = time.time() msecs = (endTime - startTime) * 1000 print("time is %d ms" % msecs) return wrapper @deco def func(a, b): print("hello,here is a func for add :") time.sleep(1) print("result is %d" % (a + b)) if __name__ == '__main__': f = func f(3, 4) # func()
使用装饰器处理异常
多个装饰器从上到下执行
1 #coding=utf-8 2 3 4 def ioerror1(fun): 5 def ioerror2(docment): 6 try: 7 fun(docment) 8 except IOError: 9 print("File is missing!") 10 return ioerror2 11 12 def valueerror1(fun): 13 def valueerror2(docment): 14 try: 15 fun(docment) 16 except ValueError: 17 pass 18 return valueerror2 19 20 @ioerror1 21 @valueerror1 22 def said(docment): 23 with open(docment) as data: 24 for each_line in data: 25 (role,spoken) = each_line.split(':',1) 26 print(role,end='') 27 print('said:',end='') 28 print(spoken,end=' ') 29 30 said('E:pyHeadFirstPythonchapter3sketch.txt')
装饰类函数,只要在内部函数添加self变量
1 import os 2 3 4 def excute_all(func): 5 def wrapper(self, *args, **kwargs): 6 xlsx_list = os.listdir(path='..//Data//') 7 for xlsx in xlsx_list: 8 if ".xlsx" in xlsx and "~" not in xlsx: 9 self.xlsx = xlsx 10 print("正在执行" + self.xlsx) 11 func(self, *args, **kwargs) 12 return wrapper 13 14 15 class TestSplit(object): 16 def __init__(self): 17 pass 18 19 @excute_all 20 def entrust(self): 21 print(self.xlsx[:-5] + '.log') 22 23 24 if __name__ == '__main__': 25 a = TestSplit() 26 a.entrust()
参考:https://blog.csdn.net/xiangxianghehe/article/details/77170585
http://www.cnblogs.com/sysnap/p/6599140.html
装饰器带参数,函数带参数
1 def get_db_info1(db_remark): 2 def real_func(fun2): 3 def handle_func(*args, **kwargs): 4 print("$$$$$$$$$$$$db_name$$$$$$$$$$$$$", db_remark) 5 kwargs["host"] = "10.139.60.156" 6 kwargs["user"] = "user" 7 kwargs["password"] = "password" 8 fun2(*args, **kwargs) 9 10 return handle_func 11 12 return real_func 13 14 15 @get_db_info1(db_remark="mysql156") 16 def execute_sql_list2(*args, **kwargs): 17 # print("###########sql#############", sql) 18 print(kwargs['host']) 19 print(kwargs['user']) 20 print(kwargs["password"]) 21 for key in args: 22 print(key) 23 24 25 if __name__ == '__main__': 26 execute_sql_list2("sql_list")
参考:https://www.cnblogs.com/sysnap/p/6599140.html
https://www.cnblogs.com/chaojiyingxiong/p/9223754.html