1. 编写有参函数装饰器
def auth(db_type):
def deco(func):
def wrapper(*args, **kwargs):
name = input('name:').strip()
psd = input('password:').strip()
if db_type == 'file':
print('基于文件验证')
if name == 'avery' and psd == '123':
print('login successful')
res = func(*args, **kwargs)
return res
else:
print('error')
elif db_type == 'mysql':
print('基于mysql验证')
res = func(*args, **kwargs)
return res
elif db_type == 'ldap':
print('基于ldap验证')
res = func(*args, **kwargs)
return res
else:
print('wrong type')
return wrapper
return deco
@auth(db_type='file') # @deco # index = deco(index) # index = wrapper
def index(x, y):
print('index->>%s:%s' % (x, y))
@auth(db_type='mysql') # deco # index = deco(index) # index = wrapper
def home(name):
print('home>>%s' % name)
@auth(db_type='ldap')
def transfer():
print('transfer')
index(2,3)
home("avery")
transfer()
2. 在文件开头声明一个空字典,然后在每个函数前加上装饰器,完成自动添加到字典的操作
d = {}
def add_dict(key):
def wrapper(func):
def inner(*args, **kwargs):
global d
d[key] = func
return func(*args, **kwargs)
return inner
return wrapper
@add_dict('1')
def index():
pass
@add_dict('2')
def home():
pass
index()
home()
print(d)
3. 编写日志装饰器
'''
实现功能如:
一旦函数f1执行,则将消息2017-07-21 11:12:11 f1 run写入到日志文件中,日志文件路径可以指定
注意:时间格式的获取
import time
time.strftime('%Y-%m-%d %X')
'''
import time
def timer(func):
def wrapper(*args, **kwargs):
file = input('filename:').strip()
with open(r'{}'.format(file), mode='at', encoding='utf-8') as f1:
f1.write(time.strftime(f'%Y-%m-%d %X {func.__name__} run
'))
res = func()
return res
return wrapper
@timer
def index():
print('Hello')
@timer
def home():
print('Home')
index()
home()
4. 基于迭代器的方式,用while循环迭代取值字符串、列表、元组、字典、集合、文件对象
str_demo = '1234'
list_demo = [1, 2, 3, 4]
tuple_demo = (1, 2, 3, 4)
dict_demo = {'k1': 1, 'k2': 2, 'k3': 3, 'k4': 4}
set_demo = {1, 2, 3}
def wrapper(func):
print('该对象为{}'.format(type(func)))
while True:
try:
print(next(func))
except StopIteration:
break
wrapper(iter(str_demo))
wrapper(iter(list_demo))
wrapper(iter(tuple_demo))
wrapper(iter(dict_demo))
wrapper(iter(set_demo))
5. 自定义迭代器实现range功能
def ranges_s(start, stop, step=1):
while start < stop:
yield start
start += step
for i in ranges_s(0, 5):
print(i)