作业错误:装饰器里竟然不调用函数?要装饰器干啥的?不就是为了扩展函数的功能???
1、编写课上讲解的有参装饰器准备明天默写
def auth(style):
def deco(func):
def wrapper(*args,**kwargs):
user = input('name:').strip()
pwd = input('password:').strip()
if style == 'file':
print('基于文件校验')
elif style == 'msql':
print('基于数据库校验')
elif style == 'ldap':
print('基于ldap校验')
else:
print('no')
res = func()
return res
return wrapper
return deco
@auth('ldap')
def func():
print('good')
func()
2:还记得我们用函数对象的概念,制作一个函数字典的操作吗,来来来,我们有更高大上的做法,在文件开头声明一个空字典,然后在每个函数前加上装饰器,完成自动添加到字典的操作
dic = {}
x = 0
def auth(d):
def outter(func):
def wrapper(*args,**kwargs):
global x
print(x)
d[str(x)] = func
x += 1
return wrapper
return outter
@auth(dic)
def func1():
pass
@auth(dic)
def func2():
pass
@auth(dic)
def func3():
pass
func1()
func2()
func3()
print(dic)
3、 编写日志装饰器,实现功能如:一旦函数f1执行,则将消息2017-07-21 11:12:11 f1 run写入到日志文件中,日志文件路径可以指定
注意:时间格式的获取
def auth(path):
def outter(func):
def wrapper(*args, **kwargs):
import time
time1 = time.strftime('%Y-%m-%d %X')
with open(r'{}'.format(path), 'a', encoding='utf-8') as f:
f.write('{} {} run
'.format(time1, func.__name__))
return wrapper
return outter
@auth('tank.txt')
def func1():
pass
func1()
4、基于迭代器的方式,用while循环迭代取值字符串、列表、元组、字典、集合、文件对象
def for1(l):
l = l.__iter__()
while True:
try:
print(l.__next__())
except:
break
l = 'abcde'
for1(l)
5、自定义迭代器实现range功能
def range_my(start,end,step = 1):
while True:
if step > 0:
if start < end:
yield start
start += step
else:
break
else:
if start > end:
yield start
start += step
else:
break
g = range_my(0,5,2)
for i in g:
print(i)