装饰器
器即函数,装饰即修饰,意指为其他函数添加新功能 装饰器定义:本质就是函数,功能是为其他函数添加新功能 装饰器涉及的知识点= 高阶函数+函数嵌套+闭包 在遵循下面两个原则的前提下为被装饰者新功能 必须遵循的原则: 1)一定不能修改源代码 2)不能修改调用方式 语法糖(格式符号):@
@timer #@timer就等同于cal=timer(cal) def cal(array): res=0 for i in array: res+=i return res cal(range(10)) ###装饰器初识### def time(func): def wrapper(): print('in the wrapper ---start') func() #实际执行原始的index print('in the wrapper ---end') return wrapper @time def index(): print('in the index') index() #执行的wrapper '''运行结果: in the wrapper ---start in the index in the wrapper ---end ''' ###实例代码### import time def timer(func): def wrapper(*args,**kwargs): start_time=time.time() res=func(*args,**kwargs) stop_time=time.time() print('run time is %s' %(stop_time-start_time)) return res return wrapper @timer def index(msg): print('in the index: ',msg) @timer def home(user,msg): print('in the home %s %s' %(user,msg)) return 1 res = home('tom',msg='xxxxx') print(res) ###运行结果### C:\Python34\python.exe E:/Python16/day4/装饰器代码.py in the home tom xxxxx run time is 0.0 Process finished with exit code 0
user_list=[ {'name':'alex','passwd':'123'}, {'name':'linhaifeng','passwd':'123'}, {'name':'wupeiqi','passwd':'123'}, {'name':'yuanhao','passwd':'123'}, ] current_user={'username':None,'login':False} def auth_deco(func): def wrapper(*args,**kwargs): if current_user['username'] and current_user['login']: res=func(*args,**kwargs) return res username=input('用户名: ').strip() passwd=input('密码: ').strip() for index,user_dic in enumerate(user_list): if username == user_dic['name'] and passwd == user_dic['passwd']: current_user['username']=username current_user['login']=True res=func(*args,**kwargs) return res break else: print('用户名或者密码错误,重新登录') return wrapper @auth_deco def index(): print('欢迎来到主页面') @auth_deco def home(): print('这里是你家') def shopping_car(): print('查看购物车啊亲') def order(): print('查看订单啊亲') print(user_list) # index() print(user_list) home() 无参装饰器--登录验证
user_list=[ {'name':'alex','passwd':'123'}, {'name':'linhaifeng','passwd':'123'}, {'name':'wupeiqi','passwd':'123'}, {'name':'yuanhao','passwd':'123'}, ] current_user={'username':None,'login':False} def auth(auth_type='file'): def auth_deco(func): def wrapper(*args,**kwargs): if auth_type == 'file': if current_user['username'] and current_user['login']: res=func(*args,**kwargs) return res username=input('用户名: ').strip() passwd=input('密码: ').strip() for index,user_dic in enumerate(user_list): if username == user_dic['name'] and passwd == user_dic['passwd']: current_user['username']=username current_user['login']=True res=func(*args,**kwargs) return res break else: print('用户名或者密码错误,重新登录') elif auth_type == 'ldap': print('巴拉巴拉小魔仙') res=func(*args,**kwargs) return res return wrapper return auth_deco #auth(auth_type='file')就是在运行一个函数,然后返回auth_deco,所以@auth(auth_type='file') #就相当于@auth_deco,只不过现在,我们的auth_deco作为一个闭包的应用,外层的包auth给它留了一个auth_type='file'参数 @auth(auth_type='ldap') def index(): print('欢迎来到主页面') @auth(auth_type='ldap') def home(): print('这里是你家') def shopping_car(): print('查看购物车啊亲') def order(): print('查看订单啊亲') # print(user_list) index() # print(user_list) home() 有参装饰器 有参装饰器--登录验证
装饰器相关参考链接:http://www.cnblogs.com/wupeiqi/articles/4980620.html
列表生成式
列表生成式即List Comprehensions,是Python内置的非常简单却强大的可以用来创建list的生成式。
举个例子,现在生成一个list[1,2,...10],可以用list(range(1,11))
>>> list(range(1,11)) [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] >>>
根据需求,想要将[1,2,...10]变为[1x1,2x2,...10x10],如何做到?
###方法一 >>> a [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] >>> a=list(range(1,11)) >>> b=[] >>> for i in a:b.append(i*i) ... >>> b [1, 4, 9, 16, 25, 36, 49, 64, 81, 100] >>> ###方法二 b = [] for i in range(1,11): b.append(i*i) print(b) '''结果: [1, 4, 9, 16, 25, 36, 49, 64, 81, 100] ''' ###方法三 for index,i in enumerate(a): a[index] =i*i print(a) '''结果为 [1, 4, 9, 16, 25, 36, 49, 64, 81, 100] ''' ###方法四 a = list(range(1,11)) a = map(lambda x:x*x,a) for i in a: print(i) '''结果为 1 4 9 16 25 36 49 64 81 100 '''
总而言之方法很多,最简单快捷的方式应该是——列表生成式,如下:
>>> a = [x * x for x in range(1, 11)] >>> a [1, 4, 9, 16, 25, 36, 49, 64, 81, 100] >>>
OK!一行搞定。除此之外,
列表生成式的其他常见用法
1)for循环后面还可以加上if判断,这样我们就可以筛选出仅偶数的平方 >>> a=[x * x for x in range(1, 11) if x % 2 == 0] >>> a [4, 16, 36, 64, 100] >>> 2)两层循环,生成全排列 >>> a=[m + n for m in 'ABC' for n in 'XYZ'] >>> a ['AX', 'AY', 'AZ', 'BX', 'BY', 'BZ', 'CX', 'CY', 'CZ'] >>> 3)其他操作 三层和三层以上的循环就很少用到了。 运用列表生成式,可以写出非常简洁的代码。例如,列出当前目录下的所有文件和目录名,可以通过一行代码实现: >>> import os # 导入os模块,模块的概念后面讲到 >>> [d for d in os.listdir('.')] # os.listdir可以列出文件和目录 ['.emacs.d', '.ssh', '.Trash', 'Adlm', 'Applications', 'Desktop', 'Documents', 'Downloads', 'Library', 'Movies', 'Music', 'Pictures', 'Public', 'VirtualBox VMs', 'Workspace', 'XCode'] for循环其实可以同时使用两个甚至多个变量,比如dict的items()可以同时迭代key和value: >>> d = {'x': 'A', 'y': 'B', 'z': 'C' } >>> for k, v in d.items(): ... print(k, '=', v) ... y = B x = A z = C 因此,列表生成式也可以使用两个变量来生成list: >>> d = {'x': 'A', 'y': 'B', 'z': 'C' } >>> [k + '=' + v for k, v in d.items()] ['y=B', 'x=A', 'z=C'] 最后把一个list中所有的字符串变成小写: >>> L = ['Hello', 'World', 'IBM', 'Apple'] >>> [s.lower() for s in L] ['hello', 'world', 'ibm', 'apple']
生成器(generator)
通过列表生成式,我们可以直接创建一个列表。但是,受到内存限制,列表容量肯定是有限的。而且,创建一个包含100万个元素的列表,不仅占用很大的存储空间,如果我们仅仅需要访问前面几个元素,那后面绝大多数元素占用的空间都白白浪费了。
所以,如果列表元素可以按照某种算法推算出来,那我们是否可以在循环的过程中不断推算出后续的元素呢?这样就不必创建完整的list,从而节省大量的空间。在Python中,这种一边循环一边计算的机制,称为生成器:generator。
什么是生成器:
可以理解为一种数据类型,这种数据类型自动实现了迭代器协议(其他的数据类型需要调用自己内置的__iter__方法),所以生成器就是可迭代对象
生成器分类及在python中的表现形式:(Python有两种不同的方式提供生成器)
1)生成器函数:常规函数定义,但是,使用yield语句而不是return语句返回结果。yield语句一次返回一个结果,在每个结果中间,挂起函数的状态,以便下次重它离开的地方继续执行
2)生成器表达式:类似于列表推导,但是,生成器返回按需产生结果的一个对象,而不是一次构建一个结果列表
生成器的优点:
Python使用生成器对延迟操作提供了支持。所谓延迟操作,是指在需要的时候才产生结果,而不是立即产生结果。这也是生成器的主要好处。
要创建一个generator,有很多种方法。第一种方法很简单,只要把一个列表生成式的[]
改成()
,就创建了一个generator:
>>> L = [x * x for x in range(10)] >>> L [0, 1, 4, 9, 16, 25, 36, 49, 64, 81] >>> g = (x * x for x in range(10)) >>> g <generator object <genexpr> at 0x1022ef630>
创建L
和g
的区别仅在于最外层的[]
和()
,L
是一个list,而g
是一个generator。我们可以直接打印出list的每一个元素,但我们怎么打印出generator的每一个元素呢?如果要一个一个打印出来,可以通过next()
函数获得generator的下一个返回值:
>>> next(g) 0 >>> next(g) 1 >>> next(g) 4 >>> next(g) 9 >>> next(g) 16 >>> next(g) 25 >>> next(g) 36 >>> next(g) 49 >>> next(g) 64 >>> next(g) 81 >>> next(g) Traceback (most recent call last): File "<stdin>", line 1, in <module> StopIteration
我们讲过,generator保存的是算法,每次调用next(g)
,就计算出g
的下一个元素的值,直到计算到最后一个元素,没有更多的元素时,抛出StopIteration
的错误。
当然,上面这种不断调用next(g)
实在是太变态了,正确的方法是使用for
循环,因为generator也是可迭代对象:
>>> g = (x * x for x in range(10)) >>> for n in g: ... print(n) ... 0 1 4 9 16 25 36 49 64 81
所以,我们创建了一个generator后,基本上永远不会调用next()
,而是通过for
循环来迭代它,并且不需要关心StopIteration
的错误。generator非常强大。如果推算的算法比较复杂,用类似列表生成式的for
循环无法实现的时候,还可以用函数来实现。
比如,著名的斐波拉契数列(Fibonacci),除第一个和第二个数外,任意一个数都可由前两个数相加得到:
1, 1, 2, 3, 5, 8, 13, 21, 34, ...
斐波拉契数列用列表生成式写不出来,但是,用函数把它打印出来却很容易:
def fib(max): n, a, b = 0, 0, 1 while n < max: print(b) a, b = b, a + b n = n + 1 return 'done'
注意,赋值语句:
a, b = b, a + b 相当于: t = (b, a + b) # t是一个tuple a = t[0] b = t[1]
但不必显式写出临时变量t就可以赋值。上面的函数可以输出斐波那契数列的前N个数:
>>> fib(6) 1 1 2 3 5 8 'done'
仔细观察,可以看出,fib
函数实际上是定义了斐波拉契数列的推算规则,可以从第一个元素开始,推算出后续任意的元素,这种逻辑其实非常类似generator。也就是说,上面的函数和generator仅一步之遥。要把fib
函数变成generator,只需要把print(b)
改为yield b
就可以了:
def fib(max): n, a, b = 0, 0, 1 while n < max: yield b a, b = b, a + b n = n + 1 return 'done'
这就是定义generator的另一种方法。如果一个函数定义中包含yield
关键字,那么这个函数就不再是一个普通函数,而是一个generator:
>>> f = fib(6) >>> f <generator object fib at 0x104feaaa0>
这里,最难理解的就是generator和函数的执行流程不一样。函数是顺序执行,遇到return
语句或者最后一行函数语句就返回。而变成generator的函数,在每次调用next()
的时候执行,遇到yield
语句返回,再次执行时从上次返回的yield
语句处继续执行。
def fib(max): n,a,b=0,0,1 while n<max: #print(b) yield b a,b = b,a+b n=n+1 return 'done' f=fib(10) print(f.__next__()) #多次调用就多次执行 print(f.__next__()) print("函数中断,做点其他事,然后继续。。。") print(f.__next__()) print(f.__next__()) '''执行结果: C:\Python35\python.exe D:/Python代码目录/Python_codeing/Python16_code/day05/生成器fib.py 1 1 函数中断,做点其他事,然后继续。。。 2 3 Process finished with exit code 0 '''
举个简单的例子,定义一个generator,依次返回数字1,3,5:
def odd(): print('step 1') yield 1 print('step 2') yield(3) print('step 3') yield(5)
调用该generator时,首先要生成一个generator对象,然后用next()
函数不断获得下一个返回值:
>>> o = odd() >>> next(o) step 1 1 >>> next(o) step 2 3 >>> next(o) step 3 5 >>> next(o) Traceback (most recent call last): File "<stdin>", line 1, in <module> StopIteration
可以看到,odd
不是普通函数,而是generator,在执行过程中,遇到yield
就中断,下次又继续执行。执行3次yield
后,已经没有yield
可以执行了,所以,第4次调用next(o)
就报错。回到fib
的例子,我们在循环过程中不断调用yield
,就会不断中断。当然要给循环设置一个条件来退出循环,不然就会产生一个无限数列出来。同样的,把函数改成generator后,我们基本上从来不会用next()
来获取下一个返回值,而是直接使用for
循环来迭代:
>>> for n in fib(6): ... print(n) ... 1 1 2 3 5 8
但是用for
循环调用generator时,发现拿不到generator的return
语句的返回值。如果想要拿到返回值,必须捕获StopIteration
错误,返回值包含在StopIteration
的value
中:
>>> g = fib(6) >>> while True: ... try: ... x = next(g) ... print('g:', x) ... except StopIteration as e: ... print('Generator return value:', e.value) ... break ... g: 1 g: 1 g: 2 g: 3 g: 5 g: 8 Generator return value: done
生成器代码示例:
######母鸡下蛋###### ##代码: def lay_eggs(num): egg_list=[] for egg in range(num): egg_list.append('蛋%s' %egg) return egg_list yikuangdan=lay_eggs(5) #我们拿到的是蛋 print(yikuangdan) def lay_eggs(num): for egg in range(num): res='蛋%s' %egg yield res print('下完一个蛋') laomuji=lay_eggs(5)#我们拿到的是一只母鸡 print(laomuji) print(laomuji.__next__()) print(laomuji.__next__()) print(laomuji.__next__()) egg_l=list(laomuji) print(egg_l) #演示只能往后不能往前 #演示蛋下完了,母鸡就死了 ##结果: C:\Python35\python.exe D:/Python代码目录/day5/迭代器.py ['蛋0', '蛋1', '蛋2', '蛋3', '蛋4'] <generator object lay_eggs at 0x0000000000D0DF68> 蛋0 下完一个蛋 蛋1 下完一个蛋 蛋2 下完一个蛋 下完一个蛋 下完一个蛋 ['蛋3', '蛋4'] Process finished with exit code 0 ######ATM取钱###### ##代码: def cash_out(amount): while amount >0: amount -= 1 yield 1 print("擦,又来取钱了。。。败家子!") ATM = cash_out(5) print("取到第一个 %s 万" % ATM.__next__()) print("花掉第一个一万") print("取到第二个 %s 万" % ATM.__next__()) print("花掉第二个一万") print("取到第三个 %s 万" % ATM.__next__()) print("花掉第三个一万!") print("取到第四个 %s 万" % ATM.__next__()) print("花掉第四个一万!") print("取到第五个 %s 万" % ATM.__next__()) print("花掉第五个一万!") print("取到第六个 %s 万" % ATM.__next__()) #到这时钱就取没了,再取就报错了 print("取到第N个 %s 万" % ATM.__next__()) ##结果: C:\Python35\python.exe D:/Python代码目录/day5/迭代器.py 取到第一个 1 万 花掉第一个一万 擦,又来取钱了。。。败家子! 取到第二个 1 万 花掉第二个一万 擦,又来取钱了。。。败家子! 取到第三个 1 万 花掉第三个一万! 擦,又来取钱了。。。败家子! 取到第四个 1 万 花掉第四个一万! 擦,又来取钱了。。。败家子! 取到第五个 1 万 花掉第五个一万! 擦,又来取钱了。。。败家子! Traceback (most recent call last): File "D:/Python代码目录/day5/迭代器.py", line 52, in <module> print("取到第六个 %s 万" % ATM.__next__()) #到这时钱就取没了,再取就报错了 StopIteration Process finished with exit code 1 ######吃包子(并联模拟)###### ##代码: import time def consumer (name): print("%s 准备吃包子啦!" %name) while True: baozi=yield print("包子[%s]来了,被[%s]吃了" %(baozi,name)) def producer(name): c = consumer('a') c2= consumer('b') c.__next__() c2.__next__() print("劳资开始做包子了!") for i in range(5): time.sleep(2) c.send(i) c2.send(i) producer('wei') ##'''运行结果: C:\Python34\python.exe E:/Python16/Python16_code/day05/吃包子(并联模拟).py a 准备吃包子啦! b 准备吃包子啦! 劳资开始做包子了! 包子[0]来了,被[a]吃了 包子[0]来了,被[b]吃了 包子[1]来了,被[a]吃了 包子[1]来了,被[b]吃了 包子[2]来了,被[a]吃了 包子[2]来了,被[b]吃了 包子[3]来了,被[a]吃了 包子[3]来了,被[b]吃了 包子[4]来了,被[a]吃了 包子[4]来了,被[b]吃了 Process finished with exit code 0 '''
生成器小结:
1)是可迭代对象
2)实现了延迟计算,省内存啊
3)生成器本质和其他的数据类型一样,都是实现了迭代器协议,只不过生成器附加了一个延迟计算省内存的好处,其余的可迭代对象可没有这点好处,记住喽!!!
迭代器
迭代器简介:
迭代器是访问集合元素的一种方式。迭代器对象从集合的第一个元素开始访问,直到所有的元素被访问完结束。迭代器只能往前不会后退,不过这也没什么,因为人们很少在迭代途中往后退。另外,迭代器的一大优点是不要求事先准备好整个迭代过程中所有的元素。迭代器仅仅在迭代到某个元素时才计算该元素,而在这之前或之后,元素可以不存在或者被销毁。这个特点使得它特别适合用于遍历一些巨大的或是无限的集合,比如几个G的文件
迭代器特点:
1)访问者不需要关心迭代器内部的结构,仅需通过next()方法不断去取下一个内容
2)不能随机访问集合中的某个值 ,只能从头到尾依次访问
3)访问到一半时不能往回退
4)便于循环比较大的数据集合,节省内存
我们已经知道,可以直接作用于for
循环的数据类型有以下几种:一类是集合数据类型,如list
、tuple
、dict
、set
、str
等;一类是generator
,包括生成器和带yield
的generator function。这些可以直接作用于for
循环的对象统称为可迭代对象:Iterable
。
可以使用isinstance()
判断一个对象是否是Iterable
对象:
>>> from collections import Iterable >>> isinstance([], Iterable) True >>> isinstance({}, Iterable) True >>> isinstance('abc', Iterable) True >>> isinstance((x for x in range(10)), Iterable) True >>> isinstance(100, Iterable) False
生成器都是Iterator
对象,但list
、dict
、str
虽然是Iterable
,却不是Iterator
。把list
、dict
、str
等Iterable
变成Iterator
可以使用iter()
函数:
>>> isinstance(iter([]), Iterator) True >>> isinstance(iter('abc'), Iterator) True
为什么list
、dict
、str
等数据类型不是Iterator
?
这是因为Python的Iterator
对象表示的是一个数据流,Iterator对象可以被next()
函数调用并不断返回下一个数据,直到没有数据时抛出StopIteration
错误。可以把这个数据流看做是一个有序序列,但我们却不能提前知道序列的长度,只能不断通过next()
函数实现按需计算下一个数据,所以Iterator
的计算是惰性的,只有在需要返回下一个数据时它才会计算。
Iterator
甚至可以表示一个无限大的数据流,例如全体自然数。而使用list是永远不可能存储全体自然数的。
生成一个迭代器:
>>> num = iter([1,2,3,4,5]) >>> num <list_iterator object at 0x000000000305E898> >>> num.__next__() 1 >>> num.__next__() 2 >>> num.__next__() 3 >>> num.__next__() 4 >>> num.__next__() 5 >>> num.__next__() #超出赋值边界报错 Traceback (most recent call last): File "<input>", line 1, in <module> StopIteration
常见访问方式对比:
l=['a','b','c'] #一:下标访问方式 print(l[0]) print(l[1]) print(l[2]) # print(l[3])#超出边界报错:IndexError #二:遵循迭代器协议访问方式 diedai_l=l.__iter__() print(diedai_l.__next__()) print(diedai_l.__next__()) print(diedai_l.__next__()) # print(diedai_l.__next__())#超出边界报错:StopIteration #三:for循环访问方式 #for循环l本质就是遵循迭代器协议的访问方式,先调用diedai_l=l.__iter__()方法,或者直接diedai_l=iter(l),然后依次执行diedai_l.next()...
...直到for循环捕捉到StopIteration终止循环 #for循环所有对象的本质都是一样的原理 for i in l:#diedai_l=l.__iter__() print(i) #i=diedai_l.next() #四:用while去模拟for循环做的事情 diedai_l=l.__iter__() while True: try: print(diedai_l.__next__()) except StopIteration: print('迭代完毕了,循环终止了') break