Fork me on GitHub
# 1、编写课上讲解的有参装饰器准备明天默写
'''
def timer(x,y,z):
def outter(func):
def wrapper(*args,**kwargs):
res=func(*args,**kwargs)
return res
return wrapper
return outter

@timer(x=1,y=2,z=3)
def info():
print('666')

info()
'''
# 2:还记得我们用函数对象的概念,制作一个函数字典的操作吗,来来来,我们有更高大上的做法,在文件开头声明一个空字典,然后在每个函数前加上装饰器,完成自动添加到字典的操作
'''
dic={'0':'drop_out(退出)'}
def userinfo(x,y):
def outter(func):
def wrapper(*args, **kwargs):
if x not in dic:
dic.setdefault(x,y)
res = func(*args, **kwargs)
return res
else:
print('{x}功能已存在'.format(x))
return wrapper
return outter

# func_dic={
# '0':'drop_out(退出)',
# '1':'login(登录)',
# '2':'transfer(转账)',
# '3':'check_banlance(查询余额)',
# '4':'withdraw(提现)',
# '5':'register(注册)'
# }
@userinfo(x='1',y='login(登录)')
def login():
print('登录')
@userinfo(x='2',y='transfer(转账)')
def transfer():
print('转账')
@userinfo(x='3',y='check_banlance(查询余额)')
def check_banlance():
print('查询余额')
@userinfo(x='4',y='withdraw(提现)')
def withdraw():
print('提现')
@userinfo(x='5',y='register(注册)')
def register():
print('注册')

login()
print(dic)
transfer()
print(dic)
check_banlance()
print(dic)
withdraw()
print(dic)
register()
print(dic)
'''
# 3、 编写日志装饰器,实现功能如:一旦函数f1执行,则将消息2017-07-21 11:12:11 f1 run写入到日志文件中,日志文件路径可以指定
# 注意:时间格式的获取
'''
import time
l=time.strftime('%Y-%m-%d %X')
def apps(x):
def outter(func):
def wrapper(*args, **kwargs):
with open('db.txt',mode='at',encoding='utf-8')as f:
f.write(x)
res = func(*args, **kwargs)
return res
return wrapper
return outter

@apps(x='{} f1 run'.format(l))
def f1():
print('f1')
f1()
'''
# 4、基于迭代器的方式,用while循环迭代取值字符串、列表、元组、字典、集合、文件对象
'''
s1='tank:100000000'
d=s1.__iter__()
print(d.__next__())

l=['tank',10000]
dl=l.__iter__()
print(dl.__next__())

t=(1,'tank')
dt=t.__iter__()
print(dt.__next__())

d={'a':1,'b':2}
dd=d.__iter__()
print(dd.__next__())

set1={1,2,3}
ds=set1.__iter__()
print(ds.__next__())

with open('db.txt',mode='r') as f:
df=f.__iter__()
print(df.__next__())
'''
# 5、自定义迭代器实现range功能
'''
def my_range(start,stop,step=1):
while start < stop:
yield start
start+=step
print('end>>:')

s=my_range(1,10,2)
print(s.__next__())
print(s.__next__())
print(s.__next__())
print(s.__next__())
print(s.__next__())
print(s.__next__())
'''
posted on 2020-03-24 15:56  OBOS  阅读(149)  评论(0编辑  收藏  举报