# 1, to explain the class has written reference decorator ready dictation tomorrow
def auth(db_type): def deco(func): def wrapper(*args,**kwargs): name = input('your name>>>: ').strip() pwd = input('your password>>>: ').strip() if db_type == 'file': print('基于文件的验证') if name == 'egon' and pwd == '123': RES = FUNC (* args, ** kwargs) return RES elif db_type == ' mysql ' : Print ( ' based authentication of mysql ' ) elif db_type == ' ldap ' : Print ( ' based authentication ldap ' ) the else : Print ( ' not supported db_type ' ) return warpper return Deco @auth(db_type='file') def index(x,y): print('index>>>%s %s'%(x,y)) @auth(db_type='mysql') def home(name): print(name) @auth(db_type='ldap') def transfer(): print('transfer')
2: Remember when we use the concept of function object, making a dictionary function of operating it, Come, come, we have more practice on the large, empty dictionary in a statement at the beginning of the file, and then add a decorator in front of each function, complete the operation automatically added to the dictionary
dic = {} def add_dic(key,value): def outter(func): def wrapper(*args,**kwargs): dic[key]=value res = func(*args,**kwargs) return res return wrapper return outter @add_dic('1',['login','登入']) def login(): pass @add_dic('2',['REGIST ' , ' registration ' ]) DEF REGIST (): Pass @add_dic ( ' . 3 ' , [ ' check_money ' , ' balance inquiry ' ]) DEF check_money (): Pass Login () REGIST () check_money () Print (DIC )
3, write the log decorator implement the functions such as: Once the function f1 performed, the message 2017-07-21 11:12:11 f1 run is written to the log file, the log file can be specified path
import time src = None def ouutar(func): def wrapper(*args,**kwargs): global src if src == None: inp_src = input('输入文件路径') src = inp_src res = func(*args,**kwargs) with open(inp_src,'at',encoding='utf-8') as f: f.write('{} f1 run'.format(time.strftime(' % Y-M-%%% X-D ' ))) Print ( ' write success ' ) return RES return warpper @ouutar DEF F1 (): Pass F1 ()
4, based on an iterative manner, the value strings, lists, tuples, dictionaries while loop iteration, set the file object
def a(obj_iterator): while True: try: print(obj_iterator.__next__()) except StopIteration: break a('123'.__iter__()) a([1,2,3].__iter__()) a({1:'a',2:'b'}.__iter__()) a((1,2,3).__iter__()) a({1,2,3}.__iter__()) with open('a.txt','rt',encoding='utf-8')as f: a(f.__iter__())
5, custom iterators implement range function
def my_range(start, stop, step=1): while start < stop: yield start start += step for i in my_range(0,5): print(i)