迭代器、生成器和装饰器
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()
用户登录验证装饰器
相关文章推荐
- python3中的描述器 生成器 迭代器 序列器 装饰器
- Python之函数(自定义函数,内置函数,装饰器,迭代器,生成器)
- Python--day4--迭代器-生成器-装饰器-目录
- python核心高级学习总结8------动态性、__slots__、生成器、迭代器、装饰、闭包
- 第4章 python闭包函数 装饰器 迭代器 生成器
- 函数进阶:闭包、装饰器、列表生成式、生成器、迭代器
- day4_装饰器、生成器、迭代器、序列化
- 2.7 学python 装饰器2 生成器 迭代器 模块time random
- Python学习之三大名器-装饰器、迭代器、生成器 推荐
- python迭代器 生成器 装饰器
- python学习笔记(5)--迭代器,生成器,装饰器,常用模块,序列化
- Python之装饰器、迭代器和生成器
- python 装饰器 上下文管理器 迭代器 生成器 描述符
- Python_Day_5装饰器、字符串格式化、序列化、内置模块、生成器、迭代器之篇
- 4.python迭代器生成器装饰器
- python is、==区别;with;gil;python中tuple和list的区别;Python 中的迭代器、生成器、装饰器
- Python之装饰器、迭代器和生成器
- Python----装饰器/生成器/迭代器
- 5.python(迭代器,装饰器,生成器,基本算法,正则)
- 老生常谈Python之装饰器、迭代器和生成器