Python学习————巩固

作业:

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:还记得我们用函数对象的概念,制作一个函数字典的操作吗,来来来,我们有更高大上的做法,在文件开头声明一个空字典,然后在每个函数前加上装饰器,完成自动添加到字典的操作

dic = {}


def makedic(name):
    def deco(func):
        dic[name] = func

​    return deco


@makedic('select')
def func1():
    print('select')

@makedic('update')
def func2():
    print('update')


print(dic)

dic.get('select')()

3、 编写日志装饰器,实现功能如:一旦函数f1执行,则将消息2017-07-21 11:12:11 f1 run写入到日志文件中,日志文件路径可以指定

注意:时间格式的获取

import time
import os


def auth(logfile):
    def deco(func):
        if not os.path.exists(logfile):
            with open(logfile, 'w', encoding='utf-8') as f:
                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\n'), func.__name__))
​            return res

​        return wrapper

​    return deco


@auth('diary.txt')
def index():
    print()

index()

4、基于迭代器的方式,用while循环迭代取值字符串、列表、元组、字典、集合、文件对象

5、自定义迭代器实现range功能

def range(start, stop, step=1):
    while start < stop:
        yield start  # start=1
        start += step  # start=3


func = range(0, 9, 1)
print(func)
for i in range(0, 9, 1):
    print(i)

===================

=本周选做作业如下====================
编写小说阅读程序实现下属功能
一:程序运行开始时显示
0 账号注册
1 充值功能
2 阅读小说

二: 针对文件db.txt,内容格式为:"用户名:密码:金额",完成下述功能
2.1、账号注册
2.2、充值功能

三:文件story_class.txt存放类别与小说文件路径,如下,读出来后可用eval反解出字典

3.1、用户登录成功后显示如下内容,根据用户选择,显示对应品类的小说编号、小说名字、以及小说的价格
"""
0 玄幻武侠
1 都市爱情
2 高效养猪36技
"""

3.2、用户输入具体的小说编号,提示是否付费,用户输入y确定后,扣费并显示小说内容,如果余额不足则提示余额不足

四:为功能2.2、3.1、3.2编写认证功能装饰器,要求必须登录后才能执行操作

五:为功能2.2、3.2编写记录日志的装饰器,日志格式为:"时间 用户名 操作(充值or消费) 金额"

附加:
可以拓展作者模块,作者可以上传自己的作品

posted @ 2020-03-24 19:48  Dimple_Y  阅读(149)  评论(0编辑  收藏  举报