# 1、 编写日志装饰器,实现功能如:一旦函数f1执行,则将消息2017-07-21 11:12:11 f1 run写入到日志文件中,日志文件路径可以指定
# 注意:时间格式的获取
import time
def outter1(x, z):
def outter(func):
def werapper(*args, **kwargs):
res = func(*args, **kwargs)
with open(z, mode='at', encoding='utf-8')as f:
a = time.strftime('%Y-%m-%d %X')
f.write(f'{a}{x}\n')
return res
return werapper
return outter
@outter1(x='fun1', z='v.txt')
def func1():
pass
func1()
@outter1(x='fun2', z='n.txt')
def func2():
pass
func2()
# 2、基于迭代器的方式,用while循环迭代取值字符串、列表、元组、字典、集合、文件对象
a = {"name": "sailan", 'age': 18, 'gender': "male"}
a1 = [1, 2, 3, 4, 5, 6, 7, 8]
a2 = (1, 2, 3, 4, 5, 6, 7, 8)
a3 = {1, 2, 3, 4, 5, 6, 7, 8}
a4 = 'sailan'
# 字典
z = a.__iter__()
while True:
try:
res = z.__next__()
print(res)
except StopIteration:
break
# 列表
z1 = a1.__iter__()
while 1:
try:
res = z1.__next__()
print(res)
except StopIteration:
break
# 元祖
z2 = a2.__iter__()
while 1:
try:
res = z2.__next__()
print(res)
except StopIteration:
break
# 集合
z3 = a3.__iter__()
while 1:
try:
res = z3.__next__()
print(res)
except StopIteration:
break
# 字符串
z4 = a4.__iter__()
while 1:
try:
res = z4.__next__()
print(res)
except StopIteration:
break
# 文件
with open('a.txt', mode='rt', encoding='utf-8')as f:
a5 = f.__iter__()
while 1:
try:
res = a5.__next__()
print(res)
except StopIteration:
break
# 3、自定义迭代器实现range功能
def my_range(start, stop, step=2):
while start < stop:
yield start
start += step
a = my_range(1, 8)
while 1:
try:
g = next(a)
print(g)
except StopIteration:
break
day15作业
最新推荐文章于 2024-05-10 20:01:00 发布