标签:
目录:
1、装饰器
2、迭代器&生成器
3、Json & pickle 数据序列化
4、软件目录结构规范
一、装饰器
定义:本质是函数,(装饰其他函数)就是为其他函数添加附加功能
原则:
1、不能修改被装饰的函数的源代码
2、不能修改被装饰的函数的调用方式
一个简单的装饰器:
1 #!/usr/bin/env python 2 # -*- coding: utf-8 -*- 3 # Author :GU 4 import time 5 def timmer(func): ##后加的一个记录运行时间的装饰器 6 def warpper(*args,**kwargs): 7 start_time= time.time() 8 func() 9 stop_time=time.time() 10 print("The func run timr is %s"%(stop_time-start_time)) 11 return warpper 12 @timmer ##把装饰器调用到函数test1函数里面去 13 def test1(): 14 time.sleep(3) 15 print("In the test1") 16 test1() 17 执行结果: 18 In the test1 19 The func run timr is 3.000171661376953
实现装饰器知识储备:
1、函数即变量
2、高阶函数
3、嵌套函数
高阶函数+嵌套函数=装饰器
知识点一:函数即变量==》函数的调用顺序
其他高级语言类似,Python 不允许在函数未声明之前,对其进行引用或者调用
①、错误的示范:
2 def foo(): 3 print (‘in the foo‘) 4 bar() 5 foo() 6 报错: 7 in the foo 8 Traceback (most recent call last): 9 File "<pyshell#13>", line 1, in <module> 10 foo() 11 File "<pyshell#12>", line 3, in foo 12 bar() 13 NameError: global name ‘bar‘ is not defined 14 ===================================== 15 def foo(): 16 print (‘foo‘) 17 bar() 18 foo() 19 def bar(): 20 print (‘bar‘) 21 报错:NameError: global name ‘bar‘ is not define
②、正确的示范
1 def bar(): 2 print (‘in the bar‘) 3 def foo(): 4 print (‘in the foo‘) 5 bar() 6 7 foo() 8 =================================== 9 def foo(): 10 print (‘in the foo‘) 11 bar() 12 def bar(): 13 print (‘in the bar‘) 14 foo() 15 执行结果: 16 in the foo 17 in the bar 18 ======================= 19 in the foo 20 in
知识点二:
高阶函数:a、把一个函数名当作实参传给另外一个函数 b、返回值中包含函数名
按a原则定义一个函数:
1 #不修改被装饰函数源代码的情况下为其添加功能 2 import time 3 def bar(): 4 time.sleep(3) 5 print(‘in the bar‘) 6 7 def test1(func): 8 start_time=time.time() 9 func() #run bar 10 stop_time=time.time() 11 print("the func run time is %s" %(stop_time-start_time)) 12 13 test1(bar) 14 执行结果: 15 in the bar 16 the func run time is 3.000171661376953
按b原则定义一个函数:
1 #不修改函数的调用方式 2 import time 3 def bar(): 4 time.sleep(3) 5 print(‘in the bar‘) 6 def test2(func): 7 print(func) 8 return func 9 10 # print(test2(bar)) 11 bar=test2(bar) 12 bar() #run bar 13 执行结果: 14 <function bar at 0x00000000007DE048> 15 in the bar
知识点三:
嵌套函数:定义:在一个函数体内创建另外一个函数,这种函数就叫内嵌函数(基于python支持静态嵌套域)
1 def foo(): 2 print(‘in the foo‘) 3 def bar(): 4 print(‘in the bar‘) 5 bar() 6 foo() 7 执行结果: 8 in the foo 9 in the bar
局部作用域和全局作用域的访问顺序
1 x=0 2 def grandpa(): 3 x=1 4 def dad(): 5 x=2 6 def son(): 7 x=3 8 print(x) 9 son() 10 dad() 11 grandpa() 12 执行结果: 13 3
一个完整的装饰器:
不带参数的:
1 import time 2 def timer(func): #timer(test1) func=test1 3 def deco(): 4 start_time=time.time() 5 func() #run test1() 6 stop_time = time.time() 7 print("the func run time is %s" %(stop_time-start_time)) 8 return deco 9 @timer #test1=timer(test1) 10 def test1(): 11 time.sleep(1) 12 print(‘in the test1‘) 13 #执行结果: 14 in the test1 15 the func run time is 1.0000572204589844
带参数的:
1 import time 2 def timer(func): #timer(test1) func=test1 3 def deco(*args,**kwargs): 4 start_time=time.time() 5 func(*args,**kwargs) #run test1() 6 stop_time = time.time() 7 print("the func run time is %s" %(stop_time-start_time)) 8 return deco 9 @timer #test1=timer(test1) 10 def test1(): 11 time.sleep(1) 12 print(‘in the test1‘) 13 @timer # test2 = timer(test2) = deco test2(name) =deco(name) 14 def test2(name,age): 15 time.sleep(1) 16 print("test2:",name,age) 17 test1() 18 test2("alex",22) 19 执行结果: 20 in the test1 21 the func run time is 1.0000572204589844 22 test2: alex 22 23 the func run time is 1.000057220458984
终极版装饰器:
user,passwd = ‘alex‘,‘abc123‘ def auth(auth_type): print("auth func:",auth_type) def outer_wrapper(func): def wrapper(*args, **kwargs): print("wrapper func args:", *args, **kwargs) if auth_type == "local": username = input("Username:").strip() password = input("Password:").strip() if user == username and passwd == password: print("\033[32;1mUser has passed authentication\033[0m") res = func(*args, **kwargs) # from home print("---after authenticaion ") return res else: exit("\033[31;1mInvalid username or password\033[0m") elif auth_type == "ldap": print("搞毛线ldap,不会。。。。") return wrapper return outer_wrapper def index(): print("welcome to index page") @auth(auth_type="local") # home = wrapper() def home(): print("welcome to home page") return "from home" @auth(auth_type="ldap") def bbs(): print("welcome to bbs page") index() print(home()) #wrapper() bbs() ###执行结果: auth func: local auth func: ldap welcome to index page wrapper func args: Username:alex Password:abc123 User has passed authentication welcome to home page ---after authenticaion from home wrapper func args: 搞毛线ldap,不会。。。。
二、迭代器&生成器
生成器:
通过列表生成式,可直接创建一个列表,但是受到内存限制,列表内容是有限的,创建一个100w元素的列表,不仅占用很大的内存,如果我们仅仅需要访问前面几个元素,那么后面大多数元素占用的空间是浪费的,所以,如果列表元素可以按照某种算法推算出来,那我们是否可以在循环列表的过程中不断推算出后续的函数,这样就没有必要创建完整的list,从而节省了大量的空间=====》》generator
创建一个简单的generator,只要把一个列表生成式的[]
改成()
,就创建了一个generator:
1 >>> l = [x * x for x in range(10)] 2 >>> l 3 [0, 1, 4, 9, 16, 25, 36, 49, 64, 81] 4 >>> g = (x * x for x in range(10)) 5 >>> g 6 <generator object <genexpr> at 0x00000000006F3048>
创建L
和g
的区别仅在于最外层的[]
和()
,L
是一个list,而g
是一个generator。
我们可以直接打印出list的每一个元素,但我们怎么打印出generator的每一个元素呢?
如果要一个一个打印出来,通过next()
函数获得generator的下一个返回值:
1 >>> next(g) 2 0 3 >>> next(g) 4 1 5 >>> next(g) 6 4 7 >>> next(g) 8 9 9 >>> next(g) 10 16 11 >>> next(g) 12 25 13 >>> next(g) 14 36 15 >>> next(g) 16 49
生成器之后在调用时才会生成相应的数据,直到计算到最后一个元素,没有更多的元素时,抛出StopIteration
的错误。
不断调用next(g)的方式不是很好
,正确的方法是使用for
循环,因为generator也是可迭代对象,如果只有一个就可以用next()方法
1 >>> for n in g: 2 ... print(n) 3 ... 4 0 5 1 6 4 7 9 8 16 9 25 10 36 11 49 12 64 13 81
generator非常强大。如果推算的算法比较复杂,用类似列表生成式的for
循环无法实现的时候,还可以用函数来实现。比如,著名的斐波拉契数列(Fibonacci),除第一个和第二个数外,任意一个数都可由前两个数相加得到:
1, 1, 2, 3, 5, 8, 13, 21, 34, ...
斐波拉契数列用列表生成式写不出来,但是,用函数把它打印出来却很容易:
1 def fib(max): 2 n, a, b = 0, 0, 1 3 while n < max: 4 print(b) 5 a, b = b, a + b ##相当于 6 n = n + 1 7 return ‘done‘ 8 fib(5) ##打印前五个数列 9 #####执行结果 10 1 11 1 12 2 13 3 14 5 15 =============== 16 a, b = b, a + b ##相当于 17 t = (b, a + b) # t是一个tuple 18 a = t[0] 19 b = t[1]
由此可以看出,fib函数实际上是定义了斐波拉契数列的推算规则,可以从第一个元素开始,推算出后续任意元素,这种逻辑其实非常类似generator,要把fib函数变成generator,只需要把print(b)改成yield b就可以了:
1 def fib(max): 2 n, a, b = 0, 0, 1 3 while n < max: 4 #print(b) 5 yield b ###返回当前状态的值 6 a, b = b, a + b 7 n = n + 1 8 return ‘done‘ 9 gen = fib(5) 10 print(gen.__next__()) 11 print(gen.__next__()) 12 print(gen.__next__()) 13 print(gen.__next__()) 14 执行结果: 15 1 16 1 17 2 18 3
上面fib的例子,在循环过程中不断调用yield,只要我们不中断程序就会一直执行,当然循环是需要设置一个条件来退出循环,不然就会产生一个无限数列出来,同样的generator后,我们基本上从来不会用next()
来获取下一个返回值,而是直接使用for
循环来迭代:
1 def fib(max): 2 n, a, b = 0, 0, 1 3 while n < max: 4 #print(b) 5 yield b 6 a, b = b, a + b 7 n = n + 1 8 return ‘done‘ 9 for i in fib(5): 10 print(i) 11 #执行结果: 12 1 13 1 14 2 15 3 16 5
但是用for循环调用generator时,发现拿不到generator的return语句的返回值,但是想要拿到返回值,必须捕获StopIteration
错误,返回值包含在StopIteration
的value中
1 def fib(max): 2 n, a, b = 0, 0, 1 3 while n < max: 4 #print(b) 5 yield b 6 a, b = b, a + b 7 n = n + 1 8 return ‘done‘ 9 g = fib(6) 10 while True: 11 try: 12 x = next(g) 13 print(‘g:‘, x) 14 except StopIteration as e: 15 print(‘Generator return value:‘, e.value) 16 break 17 ###执行结果; 18 g: 1 19 g: 1 20 g: 2 21 g: 3 22 g: 5 23 g: 8 24 Generator return value: done
通过yield实现在单线程的情况下实现并发运算
1 #!/usr/bin/env python 2 # -*- coding: utf-8 -*- 3 # Author :GU 4 import time 5 def consuner(name): 6 print("%s 准备吃包子了"%name) 7 while True: 8 baozi = yield 9 print("包子[%s]来了,被[%s]吃了"%(baozi,name)) 10 # c = consuner("haha") 11 # c.__next__() 12 13 def producer(name): 14 c = consuner("a") 15 c2 = consuner("b") 16 c.__next__() 17 c2.__next__() 18 print("老子开始准备做包子了") 19 for i in range(10): 20 time.sleep(1) 21 print("做了一个包子") 22 c.send(i) 23 c2.send(i) 24 producer("guyun") 25 #执行结果: 26 a 准备吃包子了 27 b 准备吃包子了 28 老子开始准备做包子了 29 做了一个包子 30 包子[0]来了,被[a]吃了 31 包子[0]来了,被[b]吃了 32 做了一个包子 33 包子[1]来了,被[a]吃了 34 包子[1]来了,被[b]吃了 35 做了一个包子 36 包子[2]来了,被[a]吃了 37 包子[2]来了,被[b]吃了 38 做了一个包子 39 包子[3]来了,被[a]吃了 40 包子[3]来了,被[b]吃了 41 。。。。。。。。。。。。。
迭代器:
可以直接作用于for
循环的数据类型有以下几种:
一类是集合数据类型,如list(列表)
、tuple(元组)
、dict(字典)
、set(集合)
、str(字符串)
等;
一类是generator()
,包括生成器和带yield
的generator function。
这些可以直接作用于for
循环的对象统称为可迭代对象:Iterable,
可循环的对象
可以使用isinstance()
判断一个对象是否是Iterable
对象:
1 >>> from collections import Iterable 2 >>> isinstance([],Iterable) 3 True 4 >>> isinstance({},Iterable) 5 True 6 >>> isinstance("abc",Iterable) 7 True 8 >>> isinstance((x for x in range(10)), Iterable) 9 True 10 >>> isinstance(100, Iterable) 11 False
而生成器不但可以最用于for循环,还可以被next()函数不断调用并返回下一值,知道最后抛出StopIteration错误表示无法继续返回下一个值了
*可以被next()函数调用,并不断返回下一个值得对象称为迭代器,Iterator
可以使用isinstance()判断一个对象是否是Iterator对象
1 >>> from collections import Iterator 2 >>> isinstance((x for x in range(10)), Iterator) 3 True 4 >>> isinstance([], Iterator) 5 False 6 >>> isinstance({}, Iterator) 7 False 8 >>> isinstance(‘abc‘, Iterator) 9 False
生成器都是迭代器
对象,但list
、dict
、str
虽然是可迭代的
,却不是迭代器
。
把list
、dict
、str
等可迭代对象
变成迭代器
可以使用iter()
函数:
1 >>> isinstance(iter([]), Iterator) 2 True 3 >>> isinstance(iter(‘abc‘), Iterator) 4 True
你可能会问,为什么list
、dict
、str
等数据类型不是Iterator(迭代器)
?
这是因为Python的Iterator
对象表示的是一个数据流,Iterator对象可以被next()
函数调用并不断返回下一个数据,直到没有数据时抛出StopIteration
错误。可以把这个数据流看做是一个有序序列,但我们却不能提前知道序列的长度,只能不断通过next()
函数实现按需计算下一个数据,所以Iterator
的计算是惰性的,只有在需要返回下一个数据时它才会计算。
Iterator
甚至可以表示一个无限大的数据流,例如全体自然数。而使用list是永远不可能存储全体自然数的。
小结
凡是可作用于for
循环的对象都是Iterable
类型;
凡是可作用于next()
函数的对象都是Iterator
类型,它们表示一个惰性计算的序列;
集合数据类型如list
、dict
、str
等是Iterable
但不是Iterator
,可以通过iter()
函数获得一个Iterator
对象。
Python的for
循环本质上就是通过不断调用next()
函数实现的,例如:
1 for x in [1, 2, 3, 4, 5]: 2 pass
实际完全等价于
1 # 首先获得Iterator对象: 2 it = iter([1, 2, 3, 4, 5]) 3 # 循环: 4 while True: 5 try: 6 # 获得下一个值: 7 x = next(it) 8 except StopIteration: 9 # 遇到StopIteration就退出循环 10 break
三、Json & pickle 数据序列化
用于序列化的两个模块
Json模块提供了四个功能:dumps、dump、loads、load
pickle模块提供了四个功能:dumps、dump、loads、load
1、json序列化(dumps)
1 #!/usr/bin/env python 2 # -*- coding: utf-8 -*- 3 # Author :GU 4 import json 5 info = { 6 ‘name‘:‘alex‘, 7 ‘age‘:22, 8 } 9 f = open("test.text","w") 10 f.write( json.dumps( info) ) ###用dunmps序列化 11 f.close() 12 ##执行结果: 13 {"name": "alex", "age": 22}
2、在用json反序列化(loads)
1 #!/usr/bin/env python 2 # -*- coding: utf-8 -*- 3 # Author :GU 4 import json 5 f = open("test.text","r") 6 data = json.loads(f.read()) ###loads反序列化 7 print(data["age"]) 8 ###执行结果: 9 22
这样就实现了把内存存在硬盘上,再读出来
3、、pickle序列化(dumps)
1 #!/usr/bin/env python 2 # -*- coding: utf-8 -*- 3 # Author :GU 4 import pickle 5 def sayhi(name): 6 print("hello,",name) 7 info = { 8 ‘name‘:‘alex‘, 9 ‘age‘:22, 10 "func":sayhi, 11 } 12 f = open("test.text","wb") 13 f.write( pickle.dumps( info) ) 14 f.close() 15 执行结果: 16 ?}q (X funcqc__main__ 17 sayhi 18 qX nameqX alexqX ageqKu.
4、pickle反序列化(loads)
1 #!/usr/bin/env python 2 # -*- coding: utf-8 -*- 3 # Author :GU 4 import pickle 5 def sayhi(name): 6 print("hello,",name) 7 f = open("test.text","rb") 8 data = pickle.loads(f.read()) 9 print(data["func"]("alex")) 10 执行结果: 11 hello, alex 12 None
5、dump,load序列化,反序列化
1 序列化 2 #!/usr/bin/env python 3 # -*- coding: utf-8 -*- 4 # Author :GU 5 import pickle 6 def sayhi(name): 7 print("hello,",name) 8 info = { 9 ‘name‘:‘alex‘, 10 ‘age‘:22, 11 ‘func‘:sayhi 12 } 13 f = open("test.text","wb") 14 pickle.dump(info,f) #f.write( pickle.dumps( info) ) 15 f.close() 16 ############################### 17 反序列化 18 #!/usr/bin/env python 19 # -*- coding: utf-8 -*- 20 # Author :GU 21 import pickle 22 def sayhi(name): 23 print("hello2,",name) 24 f = open("test.text","rb") 25 data = pickle.load(f) #data = pickle.loads(f.read()) 26 print(data["func"]("Alex")) 27 ##执行结果跟上面完全一样
"设计项目目录结构",就和"代码编码风格"一样,属于个人风格问题。对于这种风格上的规范,规范化能更好的控制程序结构,让程序具有更高的可读性。
设计一个层次清晰的目录结构,就是为了达到以下两点:
关于如何组织一个较好的Python工程目录结构,已经有一些得到了共识的目录结构。在Stackoverflow的这个问题上,能看到大家对Python目录结构的讨论。
假设项目名为foo,最方便快捷目录结构:
Foo/
|-- bin/ ##可执行文件目录
| |-- foo
|—conf 配置文件
|-- foo/ ##主程序目录,主要的程序逻辑
| |-- tests/ ##测试用例
| | |-- __init__.py
| | |-- test_main.py
| |
| |-- __init__.py ##空文件
| |-- main.py ##程序主入口
|
|-- docs/ ##文档
| |-- conf.py
| |-- abc.rst
|
|-- setup.py##安装部署脚本
|-- requirements.txt##依赖关系
|-- README##
简要解释一下:
bin/
: 存放项目的一些可执行文件,当然你可以起名script/
之类的也行。foo/
: 存放项目的所有源代码。(1) 源代码中的所有模块、包都应该放在此目录。不要置于顶层目录。(2) 其子目录tests/
存放单元测试代码; (3) 程序的入口最好命名为main.py
。docs/
: 存放一些文档。setup.py
: 安装、部署、打包的脚本。requirements.txt
: 存放软件依赖的外部Python包列表。README
: 项目说明文件。 除此之外,有一些方案给出了更加多的内容。比如LICENSE.txt
,ChangeLog.txt
文件等,我没有列在这里,因为这些东西主要是项目开源的时候需要用到。如果你想写一个开源软件,目录该如何组织,可以参考这篇文章。
这个我觉得是每个项目都应该有的一个文件,目的是能简要描述该项目的信息,让读者快速了解这个项目。
它需要说明以下几个事项:
在软件开发初期,由于开发过程中以上内容可能不明确或者发生变化,并不是一定要在一开始就将所有信息都补全。但是在项目完结的时候,是需要撰写这样的一个文档的。可以参考Redis源码中Readme的写法,这里面简洁但是清晰的描述了Redis功能和源码结构。
一般来说,用setup.py
来管理代码的打包、安装、部署问题。业界标准的写法是用Python流行的打包工具setuptools来管理这些事情。这种方式普遍应用于开源项目中。不过这里的核心思想不是用标准化的工具来解决这些问题,而是说,一个项目一定要有一个安装部署工具,能快速便捷的在一台新机器上将环境装好、代码部署好和将程序运行起来。
开始接触Python写项目的时候,安装环境、部署代码、运行程序这个过程全是手动完成,遇到过以下问题:
setup.py
可以将这些事情自动化起来,提高效率、减少出错的概率。"复杂的东西自动化,能自动化的东西一定要自动化。"是一个非常好的习惯。
setuptools的文档比较庞大,刚接触的话,可能不太好找到切入点。学习技术的方式就是看他人是怎么用的,可以参考一下Python的一个Web框架,flask是如何写的: setup.py
这个文件存在的目的是:
setup.py
安装依赖时漏掉软件包。 这个文件的格式是每一行包含一个包依赖的说明,通常是flask>=0.10
这种格式,要求是这个格式能被pip
识别,这样就可以简单的通过 pip install -r requirements.txt
来把所有Python包依赖都装好了。具体格式说明: 点这里。
conf.py
放在源码目录下,而是放在docs/
目录下。很多项目对配置文件的使用做法是:
import conf
这种形式来在代码中使用配置。这种做法我不太赞同:
conf.py
这个文件。配置的使用,更好的方式是,
能够佐证这个思想的是,nginx、mysql这些程序都可以自由的指定用户配置。
所以,不应当在代码中直接import conf
来使用配置文件。上面目录结构中的conf.py
,是给出的一个配置样例,不是在写死在程序中直接引用的配置文件。可以通过给main.py
启动参数指定配置路径的方式来让程序读取配置内容。当然,这里的conf.py
你可以换个类似的名字,比如settings.py
。或者你也可以使用其他格式的内容来编写配置文件,比如settings.yaml
之类的。
标签:
原文地址:http://www.cnblogs.com/youweilinux/p/5771922.html