3/24

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

def outter(db_type):
    def auth(func):
        def wrapper(*args, **kwargs):
            name = input('请输入姓名; ')
            pwd = input('请输入密码: ')
            if db_type == 'file':
                with open('pwd.txt', 'rt', encoding='utf-8')as file:
                    for line in file:
                        user_name, password = line.strip().split(':')
                        if name == user_name and pwd == password:
                            print('登录成功!')
                            res = func(*args, **kwargs)
                            return res
                    else:
                        print('登录失败!')
            elif db_type == 'MySQL':
                print('数据库我还不会')
            elif db_type == 'ldap':
                print('这个我也还不会')
            else:
                print('db_type不持支该操作')

        return wrapper

    return auth

2.在文件开头声明一个空字典,然后在每个函数前加上装饰器,完成自动添加到字典的操作

dic={}
key=0
def add_dic(func):
    def warpper(*args,**kwargs):
            global key
            dic[key]=func
            key+=1
    return warpper()

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

import time



def outter(file_path):
    def log(func):
        def wrapper(*args,**kwargs):
            res=func(*args,**kwargs)
            res = time.strftime('%Y-%m-%d %X')
            with open(file_path,'a',encoding='utf-8')as file:
                file.write(res)
        return wrapper
    return log

@outter('log.txt')
def f1(x,y):
    print('hello %s %s'%(x,y))

f1(1,2)

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

x='hello'
res1=x.__iter__()
while 1:
    try:
        print(res1.__next__())
    except StopIteration:
        break

l=[1,2,3,4,5]
res2=l.__iter__()
while 1:
    try:
        print(res2.__next__())
    except StopIteration:
        break

set1={1,2,3,4,5}
res3=set1.__iter__()
while 1:
    try:
        print(res3.__next__())
    except StopIteration:
        break

dic1={'name':'jake','age':18}
res4=dic1.__iter__()
while 1:
    try:
        print(res4.__next__())
    except StopIteration:
        break

tup1=(1,2,3,4,5)
res5=tup1.__iter__()
while 1:
    try:
        print(res5.__next__())
    except StopIteration:
        break

with open('a.txt','r',encoding='utf-8')as file:
    while 1:
        try:
            print(file.__next__())
        except StopIteration:
            break

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

def my_raneg(start,end,step):
    while start<end:
        yield start
        start+=step

num=my_raneg(1,10,2)
print(next(num))
print(next(num))
print(next(num))
print(next(num))
原文地址:https://www.cnblogs.com/bailongcaptain/p/12561104.html