您的位置:首页 > 其它

迭代器、生成器和装饰器

2017-02-15 22:02 501 查看

列表生成式

如果现在要给一个列表里的每个值都增加1,你会想到怎么做呢?

a=[2,3,4,5,6,7,8,9]

#方法一
b=[]
for i in a:
b.append(i+1)
print(b)
#方法二:
a=map(lambda x:x+1,a)
for i in b:
print(i)

#列表生成式
a = [i + 1 for i in a]
print(a)



生成器


特性:
1、只有在调用时才会生成相应的数据
2、只记录当前位置
3、只有一个__next__方法

 
通过列表生成式,我们可以直接创建一个列表。但是,受到内存限制,列表容量肯定是有限的。而且,创建一个包含100万个元素的列表,不仅占用很大的存储空间,如果我们仅仅需要访问前面几个元素,那后面绝大多数元素占用的空间都白白浪费了。

  所以,如果列表元素可以按照某种算法推算出来,那我们是否可以在循环的过程中不断推算出后续的元素呢?这样就不必创建完整的list,从而节省大量的空间。在Python 中,这种一边循环一边计算的机制,称为生成器:generator。

要创建一个generator,有很多种方法。第一种方法很简单,只要把一个列表生成式的
[]
改成
()
,就创建了一个generator:

# 用户登录验证装饰器
user,pwd="li",'123456'
def auth(auth_type):
print("The func is: %s"%auth_type)
def outer_wrapper(func):
def wrapper(*args,**kwargs):
if auth_type=='local':
username = input('Please input your username:').strip()
password = input('Please input your password:').strip()
if username == user and password == pwd:
# func()
res = func()  # 获取func的返回值
print("\033[31;1m The authentication have passed successfully\033[0m")
return res  # 返回func的返回值
else:
print("\033[31;1m The authentication didn't passed \033[0m")
elif auth_type=='ldap':
print('What is the ldap?')
else:
print('something else authentication')
return wrapper
return outer_wrapper

def index():
print("This is the index page")

#使用@调用装饰器进行装饰
@auth(auth_type="local")#调用auth(auth_type="file")后返回outer_wrapper,然后把函数名home当做实参传给outer_wrapper(outer_wrapper(home))开始调用,然后返回wrapper赋给home, 即home=outer_wrapper(home)
def home():
print("This is the home page")
return "from the home"

@auth(auth_type='ldap')
def bbs():
print("This is the bbs page")

index()
home()
print(home())
bbs()


用户登录验证装饰器
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: