2020Python作业15——装饰器2+迭代器
@2020.3.24
(Q1)
作业:
1、编写课上讲解的有参装饰器
def auth(db_type = 'file'): def inner(func): def wrapper(*args, **kwargs): inp_name = input("your name:").strip() inp_pwd = input("your password:").strip() if db_type == 'file': with open(r'db.txt', 'rt', encoding='utf-8') as f: for line in f: user, pwd, *_ = line.strip().split(':') if inp_name == user and inp_pwd == pwd: print('文件认证登录成功') return func(inp_name) else: print('用户名密码错误') elif db_type == 'mysql': func() elif db_type == 'ldap': func() else: print('该认证登录方式不存在') return wrapper return inner @auth(db_type='file') def index(name): print('welcome 【%s】' % name) @auth(db_type='mysql') def mysql_login(): print('mysql认证') @auth(db_type='ldap') def ldap_login(): print('ldap认证') index() mysql_login() ldap_login()
2:还记得我们用函数对象的概念,制作一个函数字典的操作吗,来来来,我们有更高大上的做法——
在文件开头声明一个空字典,然后在每个函数前加上装饰器,完成自动添加到字典的操作
d = {} key = 0 def add_dict(func): def wrapper(*args, **kwargs): global key d['{}'.format(key)] = func key += 1 return wrapper @add_dict def index(): pass @add_dict def home(): pass index() home() print(d)
3、 编写日志装饰器,实现功能如:一旦函数f1执行,则将消息2017-07-21 11:12:11 f1 run写入到日志文件中,日志文件路径可以指定
注意:时间格式的获取
import time
time.strftime('%Y-%m-%d %X')
import time import os def logger(logfile): def deco(func): if not os.path.exists(logfile): with open(logfile,'w'):pass def wrapper(*args,**kwargs): res=func(*args,**kwargs) with open(logfile,'a',encoding='utf-8') as f: f.write('%s %s run\n' %(time.strftime('%Y-%m-%d %X'),func.__name__)) return res return wrapper return deco @logger(logfile='milimili.log') def index(): print('index') index()
4、基于迭代器的方式,用while循环迭代取值字符串、列表、元组、字典、集合、文件对象
def wrapper(inp_type): print('输出内容为: {}'.format(type(inp_type))) while True: try: print(next(inp_type)) except StopIteration: break wrapper('123'.__iter__()) wrapper([1,2,3].__iter__()) wrapper((1,2,3).__iter__()) wrapper({'k1':1,'k2':2}.__iter__()) wrapper({1,2,3}.__iter__()) with open('a.txt', 'rt', encoding='utf-8') as f: wrapper(f.__iter__())
5、自定义迭代器实现range功能
def my_range(start, stop, step=1): while start < stop: start += step yield start for i in my_range(0,5): print(i-1)
🐱不负韶华,只争朝夕🍚