作业3月24号
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) # index(1,2) return res else: print('user or password error') 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('home->>%s' % name) @auth(db_type='ldap') def transfer(): print('transfer') index(1, 2) home('egon') transfer()
2:还记得我们用函数对象的概念,制作一个函数字典的操作吗,来来来,我们有更高大上的做法,在文件开头声明一个空字典,然后在每个函数前加上装饰器,完成自动添加到字典的操作
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()
3、 编写日志装饰器,实现功能如:一旦函数f1执行,则将消息2017-07-21 11:12:11 f1 run写入到日志文件中,日志文件路径可以指定
注意:时间格式的获取
import time
time.strftime('%Y-%m-%d %X')
def info(path): def outter(func): def wrapper(*args, **kwargs): now=time.strftime('%Y-%m-%d %X') with open('path','a',encoding='utf-8') as f: f.write(now) res = func(*args, **kwargs) return res return wrapper return outter path=input('请输入路径') @info(path) def f1(): f1()
4、基于迭代器的方式,用while循环迭代取值字符串、列表、元组、字典、集合、文件对象
#字符串 st='hello' res=st.__iter__() while 1: try: print(res.__next__()) except StopIteration: break #列表 lis=[1,2,3,4] res=lis.__iter__() while 1: try: print(res.__next__()) except StopIteration: break #元组 tup=(1,2,3,4) res=tup.__iter__() while 1: try: print(res.__next__()) except StopIteration: break #字典 dic={'a':1,'b':2} res=dic.__iter__() while 1: try: print(res.__next__()) except StopIteration: break #集合 se=(1,2,[3,4,]) res=se.__iter__() while 1: try: print(res.__next__()) except StopIteration: break #文件对象 with open('a.txt','w',encoding='utf-8') as f1: while 1: try: print(f1.__next__()) except StopIteration: break
5、自定义迭代器实现range功能
def my_range(start,stop,step): while start < stop: yield start start+=step g=my_range(1,9,1) for n in g: print(n)