# 1、编写课上讲解的有参装饰器准备明天默写
def muth(file_data):
    def login(func):
        def wrap(*args,**kwargs):
            if file_data == 'file':
                dic = {}
                username = input('请输入账号:').strip()
                userpwd = input('请输入密码:').strip()
                with open('a.txt',mode='r',encoding='utf-8') as f:
                    for i in f:
                        k,v = i.strip().split(':')
                        dic[k] = v
                    if username in dic and userpwd == dic[username]:
                        print('登陆成功')
                        res = func(*args,**kwargs)
                        return res
                    else:
                        print('账号密码错误')
            elif file_data == 'mysql':
                print('使用mysql登录成功')
                res = func(*args,**kwargs)
                return res
            elif file_data == 'ldap':
                print('使用ldap登录')
                res = func(*args,**kwargs)
                return res
            else:
                print('登录方式不对')
        return wrap
    return login
@muth('file')
def foo():
    print('hello world')
foo()
@muth('mysql')
def foo():
    print('hello world')
foo()
@muth('ldap')
def foo():
    print('hello world')
foo()
@muth('a')
def foo():
    print('hello world')
foo()
# 2:还记得我们用函数对象的概念,制作一个函数字典的操作吗,来来来,我们有更高大上的做法,在文件开头声明一个空字典,然后在每个函数前加上装饰器,完成自动添加到字典的操作
dic = {}

def make(ch):
    def wrap(func):
        def inner():
            dic[ch] = func()
            return dic[ch]
        return inner
    return wrap
@make('yu')
def select():
    return 123
@make('egon')
def update():
    return 456

select()
update()

print(dic)
# 3、 编写日志装饰器,实现功能如:一旦函数f1执行,则将消息2017-07-21 11:12:11 f1 run写入到日志文件中,日志文件路径可以指定
# 注意:时间格式的获取
# import time
# time.strftime('%Y-%m-%d %X')
import time
def file(file_path):
    def make(func):
        def wrapper(*args,**kwargs):
            with open(file_path,mode='a+',encoding='utf-8') as f:
                data_time = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))
                f.write('{} {} run\n'.format(data_time,func.__name__))
            res = func(*args, **kwargs)
            return res
        return wrapper
    return make
@file('b.txt')
def f1():
    print(1)
f1()
# 4、基于迭代器的方式,用while循环迭代取值字符串、列表、元组、字典、集合、文件对象
def data(info):
    res = iter(info)
    while True:
        try:
            print(next(res))
        except StopIteration:
            break
data('123')
data([1,2,3,4])
data((1,2,3,4))
data({1:2,3:4})
data({1,2,3,4})
with open('a.txt',mode='r',encoding='utf-8') as info:
    data(info)
# 5、自定义迭代器实现range功能
def my_range(start,stop,step):
    while start < stop:
        print(start)
        start += step
my_range(1,9,3)