python day18作业

作业:

# 1、编写课上讲解的有参装饰器准备明天默写
# 2:还记得我们用函数对象的概念,制作一个函数字典的操作吗,来来来,我们有更高大上的做法,
# 在文件开头声明一个空字典,然后在每个函数前加上装饰器,完成自动添加到字典的操作
op_dict = {}


def add_dict(dict_key):
    def wrapper(func):
        def inner(*args, **kwargs):
            op_dict[dict_key] = (func, func.__doc__)

        return inner

    return wrapper


@add_dict(1)
def f1():
    """f1功能"""
    print('f1')


@add_dict(2)
def f2():
    """f2功能"""
    print('f2')


f1()
f2()
print(op_dict)


# 3、 编写日志装饰器,实现功能如:一旦函数f1执行,则将消息2017-07-21 11:12:11 f1 run写入到日志文件中,
def dump_file(file):
    import time
    def wrapper(func):
        def inner(*args, **kwargs):
            start_time = time.strftime('%Y-%m-%d %X')
            with open(file, 'a+t', encoding='utf-8')as f:
                f.write(f'{start_time} {func} run\n')
            res = func(*args, **kwargs)
            return res

        return inner

    return wrapper


@dump_file('a.log')
def f1():
    print('f1功能')


f1()

# 注意:时间格式的获取
# import time
# time.strftime('%Y-%m-%d %X')
# 4、基于迭代器的方式,用while循环迭代取值字符串、列表、元组、字典、集合、文件对象
#  字符串
s = 'egon'
s = s.__iter__()
while True:
    try:
        print(next(s))
    except StopIteration:
        break
#  列表
l = [1, 2, 3, 4, 5, 6]
l = l.__iter__()
while True:
    try:
        print(next(l))
    except StopIteration:
        break
#  元组
t = (1, 2, 3, 4, 5)
t = t.__iter__()
while True:
    try:
        print(next(t))
    except StopIteration:
        break
# 字典
d = {}.fromkeys(range(1, 4), None)
d = iter(d)

while True:
    try:
        print(next(d))
    except StopIteration:
        break

# 集合
s = (1, 2, 3, 4)
s = s.__iter__()
while True:
    try:
        print(next(s))
    except StopIteration:
        break

#  文件对象
f = open('a.txt', 'r+t', encoding='utf-8')
while True:
    try:
        print(next(f))
    except StopIteration:
        break
f.close()


# 5、自定义迭代器实现range功能
def range(start, stop, step=1):
    while start < stop:
        yield start
        start += step


a = range(1, 5)
while True:
    try:
        print(next(a))
    except StopIteration:
        break
posted @ 2020-03-24 23:17  nick_xm  阅读(145)  评论(0编辑  收藏  举报