Python练习_装饰器、生成器_day12
装饰器
装饰器篇: 1.编写装饰器,为多个函数加上认证的功能(用户的账号密码来源于文件),要求登录成功一次,后续的函数都无需再输入用户名和密码。 def login(func): def inner(*args, **kwargs): """登录程序 """ username = input('username:') password = input('password:') if username == 'boss_gold' and password == '22222': ret = func(*args, **kwargs) # func是被装饰的函数 return ret else: print('登录失败') return inner @login def shoplist_add(): print('增加一件物品') @login def shoplist_del(): print('删除一件物品') shoplist_add() shoplist_del() # 但是这样有一样不好,就是运行了shoplist_add()之后再运行shoplist_del()还是要输入 用户名和密码。 FLAG = False def login(func): def inner(*args, **kwargs): global FLAG """登录程序 """ if FLAG: ret = func(*args, **kwargs) # func是被装饰的函数 return ret else: username = input('username:') password = input('password:') if username == 'boss_gold' and password == '22222': FLAG = True ret = func(*args, **kwargs) # func是被装饰的函数 return ret else: print('登录失败') return inner @login def shoplist_add(): print('增加一件物品') @login def shoplist_del(): print('删除一件物品') shoplist_add() shoplist_del() # 2.编写装饰器,为多个函数加上记录调用功能,要求每次调用函数都将被调用的函数名称写入文件。 def log(func): def inner(*args, **kwargs): with open('log', 'a', encoding='utf-8') as f: f.write(func.__name__ + '\n') ret = func(*args, **kwargs) return ret return inner @log def shoplist_add(): print('增加一件物品') @log def shoplist_del(): print('删除一件物品') shoplist_add()
推导式练习题:
1. 过滤掉长度小于3的字符串列表,并将剩下的转换成大写字母
1 li = ['qwer','asdf','zxcv','ty','gh','bn','uIo','UIj','plm'] 2 lis = [i.upper() for i in li if len(i) >= 3] 3 print(lis)
2. 求(x,y)其中x是0-5之间的偶数,y是0-5之间的奇数组成的元祖列表
lis = [(x,y) for x in range(0,6,2) for y in range(1,6,2)] print(lis)
3. 求M中3,6,9组成的列表M = [[1,2,3],[4,5,6],[7,8,9]]
M = [[1,2,3],[4,5,6],[7,8,9]] lis = [i[2] for i in M] print(lis)
生成器
3.处理文件,用户指定要查找的文件和内容,将文件中包含要查找内容的每一行都输出到屏幕 def check_file(filename,aim): with open(filename,encoding='utf-8') as f: #句柄 : handler,文件操作符,文件句柄 for i in f: if aim in i: yield i g = check_file('1.复习.py','生成器') for i in g: print(i.strip()) 4.写生成器,从文件中读取内容,在每一次读取到的内容之前加上‘***’之后再返回给用户。 def check_file(filename): with open(filename,encoding='utf-8') as f: #句柄 : handler,文件操作符,文件句柄 for i in f: yield '***'+i for i in check_file('1.复习.py'): print(i.strip())
默写
a. 生成器函数
获取移动平均值例子:
def init(func): def inner(*args,**kwargs): ret = func(*args,**kwargs) ret.__next__() return ret return inner @init def average(): average = 0 count = 0 sum = 0 while 1: num = yield average sum += num count += 1 average = sum/count ret = average() print(ret.send(10)) print(ret.send(20))