# 作业:
# 1、编写课上讲解的有参装饰器准备明天默写
def auth(db_type):
def deco(func):
def wrapper(*args, **kwargs):
name = input('your name>>>: ').strip()
pwd = input('your password>>>: ').strip()
if db_type == 'file':
print('基于文件的验证')
if name == 'egon' and pwd == '123':
res = func(*args, **kwargs)
return res
else:
print('user or password error')
elif db_type == 'mysql':
print('基于mysql的验证')
elif db_type == 'ldap':
print('基于ldap的验证')
else:
print('不支持该db_type')
return wrapper
return deco
@auth(db_type='file')
def index(x, y):
print('index->>%s:%s' % (x, y))
@auth(db_type='mysql')
def home(name):
print('home->>%s' % name)
@auth(db_type='ldap')
def transfer():
print('transfer')
index(1, 2)
home('egon')
transfer()
# 2:还记得我们用函数对象的概念,制作一个函数字典的操作吗,来来来,我们有更高大上的做法,
# 在文件开头声明一个空字典,然后在每个函数前加上装饰器,完成自动添加到字典的操作
dic = {}
k=0
def indic(func):
def wrapper(*args, **kwargs):
res=func(*args, **kwargs)
global k
dic[k] = func
k+=1
return res
return wrapper
@indic
def recharge():
print('充值')
@indic
def transfer():
print('转账')
@indic
def withdraw():
print('提现')
@indic
def balance_inquiry():
print('余额查询')
recharge()
transfer()
withdraw()
balance_inquiry()
print(dic)
# 3、 编写日志装饰器,实现功能如:一旦函数f1执行,则将消息2017-07-21 11:12:11 f1 run写入到日志文件中,
# 日志文件路径可以指定
# 注意:时间格式的获取
import time
a = time.strftime('%Y-%m-%d %X')
# from functools import wraps
def file(way):
def indic(func):
# @wraps(func)
def wrapper(*args, **kwargs):
res = func(*args, **kwargs)
with open(f'{way}', 'at', encoding='utf-8')as x:
x.write(f'{a} {func} run\n')
return res
return wrapper
return indic
@file(r'D:\cool\login')
def f1():
print('我超帅')
f1()
# 4、基于迭代器的方式,用while循环迭代取值字符串、列表、元组、字典、集合、文件对象
s='asdsfdgfd'
s=[1,2,3,4,5,6]
s=(1,2,3,4,5,6)
s={1:1,2:2,3:3}
s={1,2,3,4,5,6}
with open(r'D:\cool\login','rt',encoding='utf-8')as x:
s=x.read()
a=iter(s)
while 1:
try:
print(next(a))
except StopIteration:
break
# 5、自定义迭代器实现range功能
def m_range(str,stp,ste):
while str < stp:
yield str
str+=ste
for x in m_range(1,10,2):
print(x)