前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >装饰器、生成器,迭代器、Json & pickle 数据序列化

装饰器、生成器,迭代器、Json & pickle 数据序列化

作者头像
coders
发布2018-01-04 11:45:28
5670
发布2018-01-04 11:45:28
举报
文章被收录于专栏:coder修行路coder修行路

1、 列表生成器:代码例子

代码语言:javascript
复制
1 a=[i*2 for i in range(10)]
2 print(a)
3 
4 运行效果如下:
5 D:\python35\python.exe D:/python培训/s14/day4/列表生成式.py
6 [0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
7 
8 Process finished with exit code 0

2、高阶函数

变量可以指向函数,函数的参数能接受变量,即把一个函数名当做实参传给另外一个函数 

返回值中包涵函数名 

代码例子:

代码语言:javascript
复制
 1 def test():
 2     print("int the test")
 3 
 4 def test2(func):
 5     print("in the test2")
 6     print(func)
 7     func()
 8 
 9 test2(test)
10 运行效果如下:
11 D:\python35\python.exe D:/python培训/s14/day4/高阶函数.py
12 in the test2
13 <function test at 0x000000000110E268>  #这里是test的内存地址
14 int the test
15 
16 Process finished with exit code 0

3、装饰器

 装饰器:本质是函数,(装饰其他函数)就是为其他函数添加附加功能

装饰器原则:

a.不能修改被装饰的函数的源代码

b.不能修改被装饰的函数的调用方式

实现装饰器的知识储备:

a、函数即“变量”

b、高阶函数

c、嵌套函数

高阶函数+嵌套函数=====装饰器

高阶函数:

a.把一个函数名当做实参传给另外一个函数

b.返回值中包含函数名

代码例子

代码语言:javascript
复制
 1 import  time
 2 def timeer(func):
 3     def warpper():
 4         start_time=time.time()
 5         func()
 6         stop_time=time.time()
 7         print("the fun runn time is %s" %(stop_time-start_time))
 8     return warpper
 9 @timeer
10 def test1():
11     time.sleep(3)
12     print("in the test1")
13 
14 test1()
15 运行结果如下:
16 D:\python35\python.exe D:/python培训/s14/day4/装饰器.py
17 in the test1
18 the fun runn time is 3.000171661376953
19 
20 Process finished with exit code 0

带参数的装饰器

代码语言:javascript
复制
 1 import time
 2 
 3 def timer(func):
 4     def deco(*args,**kwargs):
 5         start_time=time.time()
 6         func(*args,**kwargs)
 7         stop_time=time.time()
 8         print("the func runn time is %s" %(stop_time-start_time))
 9     return deco
10 
11 @timer  #test1 = timer(test1)
12 def test1():
13     time.sleep(3)
14     print("in the test1")
15 
16 @timer
17 
18 def test2(name,age):
19     print("name:%s,age:%s" %(name,age))
20 
21 test1()
22 test2("zhaofan",23)
23 运行结果如下:
24 
25 D:\python35\python.exe D:/python培训/s14/day4/装饰器3.py
26 in the test1
27 the func runn time is 3.000171661376953
28 name:zhaofan,age:23
29 the func runn time is 0.0
30 
31 Process finished with exit code 0

终极版的装饰器

代码语言:javascript
复制
 1 import time
 2 user,passwd = "zhaofan","123"
 3 def auth(auth_type):
 4     print("auth func:",auth_type)
 5     def outer_wrapper(func):
 6         def wrapper(*args,**kwargs):
 7             if auth_type=="local":
 8                 username = input("Username:").strip()
 9                 password = input("Password:").strip()
10                 if user == username and passwd== password:
11                     print("\033[32;1mUser has passed authentication\033[0m")
12                     res = func(*args,**kwargs)
13                     print("------after authentication")
14                     return res
15                 else:
16                     exit("\033[31;1mInvalid username or password\033[0m")
17             elif auth_type=="ldap":
18                 print("没有ldap")
19         return wrapper
20     return outer_wrapper
21 
22 def index():
23     print("welcome to index page")
24 @auth(auth_type="local")
25 def home():
26     print("welcome to home page")
27     return "from home"
28 @auth(auth_type="ldap")
29 def bbs():
30     print("welcome to bbs page")
31 
32 index()
33 print(home())
34 bbs()
35 
36 
37 运行结果如下:
38 D:\python35\python.exe D:/python培训/s14/day4/装饰器4.py
39 auth func: local
40 auth func: ldap
41 welcome to index page
42 Username:zhaofan
43 Password:123
44 User has passed authentication
45 welcome to home page
46 ------after authentication
47 from home
48 没有ldap
49 
50 Process finished with exit code 0

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

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

代码语言:javascript
复制
 1 a = [x for x in range(10)]
 2 print(a)
 3 
 4 g=(x for x in range(10))
 5 print(g)
 6 运行结果如下:
 7 D:\python35\python.exe D:/python培训/s14/day4/生成器.py
 8 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
 9 <generator object <genexpr> at 0x0000000000B01DB0>
10 
11 Process finished with exit code 0

生成器只有一个方法:__next__()

generator保存的是算法,每次调用next(g),就计算出g的下一个元素的值,直到计算到最后一个元素,没有更多的元素时,抛出StopIteration的错误。

代码语言:javascript
复制
 1 g=(x for x in range(10))
 2 
 3 for i in g:
 4     print(i)
 5 
 6 
 7 运行结果如下:
 8 
 9 D:\python35\python.exe D:/python培训/s14/day4/生成器的调用.py
10 0
11 1
12 2
13 3
14 4
15 5
16 6
17 7
18 8
19 9
20 
21 Process finished with exit code 0

5、可以直接作用于for循环的数据类型有以下几种

一类是集合数据类型,如listtupledictsetstr等;

一类是generator,包括生成器和带yield的generator function。

这些可以直接作用于for循环的对象统称为可迭代对象:Iterable

可以使用isinstance()判断一个对象是否是Iterable对象

可以被next()函数调用并不断返回下一个值的对象称为迭代器:Iterator

生成器都是Iterator对象,但listdictstr虽然是Iterable,却不是Iterator

凡是可作用于for循环的对象都是Iterable类型;

凡是可作用于next()函数的对象都是Iterator类型,它们表示一个惰性计算的序列;

集合数据类型如listdictstr等是Iterable但不是Iterator,不过可以通过iter()函数获得一个Iterator对象。

6、json和pickle

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2016-08-19 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档