# 1、编写课上讲解的有参装饰器准备明天默写
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('基于mysql的验证') elif db_type == 'ldap': print('基于ldap的验证') else: print('不支持该db_type') return wrapper 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:还记得我们用函数对象的概念,制作一个函数字典的操作吗,来来来,我们有更高大上的做法,在文件开头声明一个空字典,然后在每个函数前加上装饰器,完成自动添加到字典的操作
func_dic = {} def outer(x): def wrapper(func): # func --> login, func --> register func_dic[x] = func # {'1': login, '2': register} def inner(*args, **kwargs): res = func(*args, **kwargs) return res return inner return wrapper @outer('1') # ---> @wrapper def login(): pass @outer('2') def register(): pass print(func_dic)
3、 编写日志装饰器,实现功能如:一旦函数f1执行,则将消息2017-07-21 11:12:11 f1 run写入到日志文件中,日志文件路径可以指定
import time def add_log_wrapper(func): def inner(*args, **kwargs): with open('log.txt', 'a', encoding='utf-8') as f: now_time = time.strftime('%Y-%m-%d %X') func_name = func.__name__ log_str = f'{now_time} {func_name} run ' print(log_str) f.write(log_str) res = func(*args, **kwargs) # 被装饰对象的调用 return res return inner @add_log_wrapper def f1(): # time.sleep(10) print('我是f1函数的执行...') @add_log_wrapper def f2(): print('我是f2函数的执行') # f1() f2()
4、基于迭代器的方式,用while循环迭代取值字符串、列表、元组、字典、集合、文件对象
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、自定义迭代器实现range功能
def my_range(start, stop, step=1): while start < stop: yield start start += step for i in my_range(0,5): print(i)