day15作业

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

import  time
from functools import  wraps

def outter(func):
    @wraps(func)
    def inner(*args,**kwargs):
        with open("log.txt",'a+',encoding="utf-8") as f:
            run_time = time.strftime('%Y-%m-%d %X')
            f.write("%s函数在%s被执行"%(func.__name__,run_time))
        res = func(*args,**kwargs)
        return res
    return inner

@outter
def f1():
    print("f1做了点什么....")

f1()

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

str1 = "abcde"
l1 = ["a","b","c","d","e"]
t1= ("a","b","c","d","e")
d1 = {"1":"a","2":"b","3":"c","4":"d","5":"e",}
set1 = {"a","b","c","d","e"}

iterable_list = [set1,l1,t1,d1,set1]

for iterable in iterable_list:
    res = iterable.__iter__()
    print(res)
    while True:
        try:
            print(res.__next__())
        except StopIteration:
            break

with open("log.txt",'r',encoding="utf-8") as  f:
    res = f.__iter__()
    print(res)
    while True:
        try:
            print(res.__next__())
        except StopIteration:
            break

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

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

res = my_range(2,5)
for i in res:
    print(i)
原文地址:https://www.cnblogs.com/panwenbin-logs/p/13363703.html