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

简介: 1、 列表生成器:代码例子 1 a=[i*2 for i in range(10)] 2 print(a) 3 4 运行效果如下: 5 D:\python35\python.exe D:/python培训/s14/day4/列表生成式.

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

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、高阶函数

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

返回值中包涵函数名 

代码例子:

 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.返回值中包含函数名

 

 

 

代码例子

 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

带参数的装饰器

 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

终极版的装饰器

 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。

 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的错误。

 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

 

所有的努力都值得期许,每一份梦想都应该灌溉!
目录
相关文章
|
2天前
|
XML JSON API
转Android上基于JSON的数据交互应用
转Android上基于JSON的数据交互应用
|
3天前
|
存储 JSON 数据挖掘
python序列化和结构化数据详解
python序列化和结构化数据详解
11 0
|
3天前
|
XML 存储 JSON
c#XML、JSON的序列化和反序列化,看完你就懂了
c#XML、JSON的序列化和反序列化,看完你就懂了
8 0
|
4天前
|
JSON Java Linux
【探索Linux】P.30(序列化和反序列化 | JSON序列化库 [ C++ ] )
【探索Linux】P.30(序列化和反序列化 | JSON序列化库 [ C++ ] )
20 2
|
9天前
|
JSON JavaScript Java
从前端Vue到后端Spring Boot:接收JSON数据的正确姿势
从前端Vue到后端Spring Boot:接收JSON数据的正确姿势
22 0
|
12天前
|
JSON 数据格式 Python
Python标准库中包含了json模块,可以帮助你轻松处理JSON数据
【4月更文挑战第30天】Python的json模块简化了JSON数据与Python对象之间的转换。使用`json.dumps()`可将字典转为JSON字符串,如`{&quot;name&quot;: &quot;John&quot;, &quot;age&quot;: 30, &quot;city&quot;: &quot;New York&quot;}`,而`json.loads()`则能将JSON字符串转回字典。通过`json.load()`从文件读取JSON数据,`json.dump()`则用于将数据写入文件。
17 1
|
12天前
|
JSON 数据格式 Python
Python处理JSON数据
【4月更文挑战第30天】该内容介绍了Python处理JSON数据的三个方法:1)使用`json.loads()`尝试解析字符串以验证其是否为有效JSON,通过捕获`JSONDecodeError`异常判断有效性;2)通过`json.dumps()`的`indent`参数格式化输出JSON数据,使其更易读;3)处理JSON中的日期,利用`dateutil`库将日期转换为字符串进行序列化和反序列化。
23 4
|
15天前
|
存储 JSON 数据处理
|
16天前
|
JSON 编译器 Go
Golang深入浅出之-结构体标签(Tags):JSON序列化与反射应用
【4月更文挑战第22天】Go语言结构体标签用于添加元信息,常用于JSON序列化和ORM框架。本文聚焦JSON序列化和反射应用,讨论了如何使用`json`标签处理敏感字段、实现`omitempty`、自定义字段名和嵌套结构体。同时,通过反射访问标签信息,但应注意反射可能带来的性能问题。正确使用结构体标签能提升代码质量和安全性。
15 0
|
16天前
|
JSON 数据可视化 定位技术
python_将包含汉字的字典数据写入json(将datav的全省数据中的贵州区域数据取出来)
python_将包含汉字的字典数据写入json(将datav的全省数据中的贵州区域数据取出来)
19 0