作业 —— day18

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 == 'xxq' and pwd == '123':
                    print('Login Successful!')
                    res = func(*args, **kwargs)
                    return res
                else:
                    print('Username 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')  # @deco # index=deco(index) # index=wrapper
def index(x, y):
    print('index->>%s:%s' % (x, y))

@auth(db_type='mysql')  # @deco # home=deco(home) # home=wrapper
def home(name):
    print('home->>%s' % name)

@auth(db_type='ldap')  # 账号密码的来源是ldap
def transfer():
    print('transfer')
    
index(1, 2)
home('egon')
transfer()

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

d = {}
key = 0
def add_dict(func):
    def wrapper(*args, **kwargs):
        global key
        d['{}'.format(key)] = func
        key += 1
    return wrapper

@add_dict
def index():
    pass
@add_dict
def home():
    pass
index()
home()

print(d)

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

注意:时间格式的获取

import time
time.strftime('%Y-%m-%d %X')
import time


def timmer(func):
    def warpper(*args, **kwargs):
        func(*args, **kwargs)
        file_path = input("请输入文件路径:")
        with open(f"{file_path}", "a", encoding="utf-8") as f:
            f.write(time.strftime(f'%Y-%m-%d %X {func.__name__} run\n'))

    return warpper


@timmer
def f1():
    print("我是f1")


@timmer
def f2():
    print("我是f2")


f1()
f2()

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

str_demo = '1234'
list_demo = [1, 2, 3, 4]
tuple_demo = (1, 2, 3, 4)
dict_demo = {'k1': 1, 'k2': 2, 'k3': 3, 'k4': 4}
set_demo = {1, 2, 3}


def wrapper(inp_type):
    print('这是 {}类型'.format(type(inp_type)))
    while True:
        try:
            print(next(inp_type))
        except StopIteration:
            break

wrapper(str_demo.__iter__())
wrapper(list_demo.__iter__())
wrapper(tuple_demo.__iter__())
wrapper(dict_demo.__iter__())
wrapper(set_demo.__iter__())

with open('a.txt', 'rt', encoding='utf-8') as f:
    wrapper(f.__iter__())

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

def new_range(start, stop, step=1):
    while start < stop:
        print(start)
        start += step

res = new_range(1, 10, 1)
print(res)
posted @ 2020-03-24 23:10  轻描丨淡写  阅读(226)  评论(0编辑  收藏  举报