首页 > 代码库 > python--有参装饰器、迭代器
python--有参装饰器、迭代器
import time
import random
from functools import wraps
def timmer(func):
@wraps(func)
def wrapper():
# wrapper.__doc__=func.__doc__
start_time = time.time()
func()
stop_time=time.time()
print(‘run time is %s‘ %(stop_time-start_time))
# wrapper.__doc__=func.__doc__
return wrapper
@timmer
def index():
‘index function‘
time.sleep(3)
print(‘welecome to index page‘)
print(index.__doc__)
# index()
# print(index.__doc__)
# def foo():
# ‘foo function------------>‘
# pass
#
# print(help(foo))
# def foo():
# ‘foo fuction‘
# print(foo.__doc__)
# foo.__doc__=‘asdfasdfasdfasdfsadfasdfasdfsadfasdfasfas‘
# pass
# print(help(foo))
# print(foo.__doc__)
# foo.__doc__=‘abcdefg‘
# print(foo.__doc__)
# print(help(foo))
#
# foo()
# print(foo.__doc__)
有参装饰器
db_path=r‘C:\Users\Administrator\PycharmProjects\python5期\day8\db.txt‘
login_dic={
‘user‘:None,
‘status‘:False,
}
# def deco(auth_type=‘file‘):
# def auth(func):
# def wrapper(*args,**kwargs):
# if auth_type == ‘file‘:
# if login_dic[‘user‘] and login_dic[‘status‘]:
# res = func(*args, **kwargs)
# return res
#
# name=input(‘your name: ‘)
# password=input(‘your password: ‘)
# with open(db_path,‘r‘,encoding=‘utf-8‘) as f:
# user_dic=eval(f.read())
#
# if name in user_dic and password == user_dic[name]:
# print(‘login ok‘)
# login_dic[‘user‘]=name
# login_dic[‘status‘]=True
# res=func(*args,**kwargs)
# return res
# else:
# print(‘login err‘)
# elif auth_type == ‘ldap‘:
# print(‘ldap认证方式‘)
# elif auth_type == ‘mysql‘:
# print(‘mysql认证方式‘)
# else:
# print(‘不知到的认证方式‘)
# return wrapper
# return auth
#
# @deco(auth_type=‘abc‘) #@auth #index=auth(index)
# def index():
# print(‘welecome to index‘)
#
# @deco(auth_type=‘ldap‘)
# def home(name):
# print(‘welecome %s to home page‘ %name)
#
#
# index()
#
# home(‘egon‘)
def deco(auth_type=‘file‘):
def auth(func):
def wrapper(*args,**kwargs):
if auth_type == ‘file‘:
print(‘文件的认证方式‘)
elif auth_type == ‘ldap‘:
print(‘ldap认证方式‘)
elif auth_type == ‘mysql‘:
print(‘mysql认证方式‘)
else:
print(‘不知到的认证方式‘)
return wrapper
return auth
@deco(auth_type=‘abc‘) #@auth #index=auth(index)
def index():
print(‘welecome to index‘)
@deco(auth_type=‘ldap‘)
def home(name):
print(‘welecome %s to home page‘ %name)
index()
home(‘egon‘)
#缓存多个不同网站的内容:
#思路:hash每个url,用得到的值做成文件名,一个网站一个文件名,
# 然后每次根据传进来的url进行hash得到的结果去寻找文件
迭代器
- 迭代:
- 重复
- 下一次重复是基于上一次的结果
‘‘‘
python为了提供一种不依赖于索引的迭代方式,
python会为一些对象内置__iter__方法
obj.__iter__称为可迭代的对象
‘‘‘
obj.__iter__() 得到的结果就是迭代器
得到的迭代器:既有__iter__又有一个__next__方法
# d={‘a‘:1,‘b‘:2,‘c‘:3}
#
# i=d.__iter__() #i叫迭代器
# print(i)
# print(i.__next__())
# print(i.__next__())
# print(i.__next__())
# print(i.__next__()) #StopIteration
迭代器的优点:
- 1:提供了一种不依赖于索引的取值方式
- 2:惰性计算。节省内存
迭代器的缺点:
- 1:取值不如按照索引取值方便
- 2:一次性的。只能往后走不能往前退
- 3:无法获取长度
# for item in l: #i=l.__iter__()
# print(item)
python--有参装饰器、迭代器