3.24迭代器生成器作业
编写课上讲解的有参装饰器
def auth(db_type): def wrapper(func): def inner(*args, **kwargs): name = input('name: ').strip() pwd = input('pwd: ').strip() if db_type == 'file': print('文件验证登录') if (name, pwd) == ('egon', '123'): print('登录成功') res = func(*args, **kwargs) return res else: print('用户名或密码错误') elif db_type == 'file': print('文件验证登录') if (name, pwd) == ('egon', '123'): print('登录成功') res = func(*args, **kwargs) return res else: print('用户名或密码错误') return inner return wrapper @auth('file') def index(): print('123') index()
还记得我们用函数对象的概念,制作一个函数字典的操作吗
来来来,我们有更高大上的做法,在文件开头声明一个空字典
然后在每个函数前加上装饰器,完成自动添加到字典的操作
cmd_dict = {} def append2dict(tips): def wrapper(func): def inner(*args, **kwargs): index = len(cmd_dict) + 1 cmd_dict[str(index)] = (tips, func) return inner return wrapper def auto_append(): my_func = {k: v for k, v in globals().items() if callable(v) if k not in {'append2dict', 'auto_append'}} for func in my_func.values(): func() @append2dict(tips='登录') def login(): print('this is login') @append2dict('注册') def register(): print('this is register') auto_append() while 1: for k, v in cmd_dict.items(): print(f'{k}-{v[0]}'.center(20, '-')) cmd = input('请输出编号:').strip() if cmd not in cmd_dict: print('重新输入') continue func = cmd_dict.get(cmd)[1] func()
编写日志装饰器,实现功能如:一旦函数f1执行,则将消息2017-07-21 11:12:11 f1 run写入到日志文件中,日志文件路径可以指定。注意:时间格式的获取
import time def my_log(file_path): def wrapper(func): def inner(*args, **kwargs): now = time.strftime('%Y-%m-%d %H:%M:%S') msg = f'{now} {func.__name__} run\n' with open(file_path, 'at', encoding='utf-8') as f: f.write(msg) res = func(*args, **kwargs) return res return inner return wrapper @my_log('log.txt') def f1(): print('i am f1') f1()
4、基于迭代器的方式,用while循环迭代取值字符串、列表、元组、字典、集合、文件对象
my_obj = '2333' my_obj_i = my_obj.__iter__() while True: try: print(my_obj_i.__next__()) except StopIteration: break
my_obj = [1,2,3] my_obj_i = my_obj.__iter__() while True: try: print(my_obj_i.__next__()) except StopIteration: break
my_obj = (4,5,6) my_obj_i = my_obj.__iter__() while True: try: print(my_obj_i.__next__()) except StopIteration: break
my_obj = {1:1, 2:2, 3:3} my_obj_i = my_obj.__iter__() while True: try: print(my_obj_i.__next__()) except StopIteration: break
my_obj = {1,2,3} my_obj_i = my_obj.__iter__() while True: try: print(my_obj_i.__next__()) except StopIteration: break
with open('aaa.txt', mode='rt', encoding='utf-8') while True: try: print(f.__next__()) except StopIteration: break
5自定义迭代器实现range功能
def my_range(start, end, step=1): while start < end: yield start start += step g = my_range(1,5) for i in g: print(i)