python 3/24作业

作业:
1、编写课上讲解的有参装饰器准备明天默写

def auth(db_type = 'file'):
    def inner(func):
        def wrapper(*args, **kwargs):
            inp_name = input("请输入用户名:>>>").strip()
            inp_pwd = input("请输入密码:>>>").strip()
            if db_type == 'file':
                with open('file.txt', 'r', 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(*args, **kwargs)
                    else:
                        print('用户名密码错误')
            elif db_type == 'mysql':
                func(*args, **kwargs)
            elif db_type == 'ldap':
                func(*args, **kwargs)
            else:
                print('该认证登录方式不存在')
        return wrapper
    return inner
@auth(db_type='file')
def index():
    print('welcome to index page')

@auth(db_type='mysql')
def mysql_login():
    print('from mysql认证')

@auth(db_type='ldap')
def ldap_login():
    print('from ldap认证')

index()
mysql_login()
ldap_login()

 


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

 

dic_menu_use={}
def append_dic(count):
    def wrapper(func):
        global dic_menu_use
        dic_menu_use[count]=[func.__doc__,func]
    return wrapper

@append_dic(0)
def user_login():
    """登录"""
    print("登录功能")

@append_dic(1)
def user_re():
    """注册"""
    print("注册功能")

@append_dic(2)
def user_out():
    """退出"""
    print("退出功能")

print(dic_menu_use)
//执行结果
{0: ['登录', <function user_login at 0x0000018BCE0137B8>], 1: ['注册', <function user_re at 0x0000018BCE0138C8>], 2: ['退出', <function user_out at 0x0000018BCE0136A8>]}

 

3、 编写日志装饰器,实现功能如:一旦函数f1执行,则将消息2017-07-21 11:12:11 f1 run写入到日志文件中,日志文件路径可以指定
注意:时间格式的获取
import time
time.strftime('%Y-%m-%d %X')

import time
def w_log(func):
    def wrapper(*args,**kwargs):
        with open("access.txt","a",encoding="utf-8") as f:
            f.write("{},{} run".format(time.strftime('%Y-%m-%d %X'),func.__name__))
        res=func(*args,**kwargs)
        return res
    return wrapper

@w_log
def f1():
    print("函数 f1 执行")

f1()

 

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

#字符串循环迭代取值
str="hello world"
str_iter=str.__iter__()
while True:
    try:
        print(next(str_iter))
    except StopIteration:
        break

#列表循环迭代取值
l=[1,2,3,4,5]
l_iter=l.__iter__()
while True:
    try:
        print(next(l_iter))
    except StopIteration:
        break

#元组循环迭代取值
t=(1,2,3,4,5)
t_iter=t.__iter__()
while True:
    try:
        print(next(t_iter))
    except StopIteration:
        break

#字典循环迭代取值
d={"name":"egon","age":18,"sex":"man"}
d_iter=d.__iter__()
while True:
    try:
        print(d[next(d_iter)])
    except StopIteration:
        break

#集合循环迭代取值
s={"egon",18,"man"}
s_iter=s.__iter__()
while True:
    try:
        print(next(s_iter))
    except StopIteration:
        break

#文件对象循环迭代取值
f=open("file.txt","r")
f_iter=f.__iter__()
while True:
    try:
        print(next(f_iter),end="")
    except StopIteration:
        break
f.close()

 


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

def my_range(start,end,step=1):
    while start < end:
        try:
            yield start
            start+=step
        except StopIteration:
            break
res=my_range(0,10)
for i in res:
    print(i)

#执行结果
0
1
2
3
4
5
6
7
8
9

 

posted @ 2020-03-24 16:47  耗油炒白菜  阅读(182)  评论(0编辑  收藏  举报