《Python核心技术与实战》笔记1
《Python核心技术与实战》笔记2
《Python核心技术与实战》笔记3
编码风格
-
《8 号 Python 增强规范》(Python Enhacement Proposal #8),简称 PEP8;
-
# 错误示例 adict = { i: i * 2 for i in xrange(10000000)} for key in adict.keys(): print("{0} = {1}".format(key, adict[key])) # keys() 方法会在遍历前生成一个临时的列表,导致上面的代码消耗大量内存并且运行缓慢。正确的方式,是使用默认的 iterator。默认的 iterator 不会分配新内存,也就不会造成上面的性能问题 # 正确示例 for key in adict:
-
PEP 8 规范告诉我们,请选择四个空格的缩进,不要使用 Tab,更不要 Tab 和空格混着用。
-
PEP 8 规定,全局的类和函数的上方需要空两个空行,而类的函数之间需要空一个空行。
-
Python 中我们可以使用
#
进行单独注释,请记得要在#
后、注释前加一个空格。
合理利用assert
assert 1 == 2
assert 1 == 2, 'ersaijun:assertion is wrong'
# 抛出异常 AssertionError
# 输出
AssertionError: ersaijun:assertion is wrong
def func(input):
assert isinstance(input, list), 'input must be type of list'
# 下面的操作都是基于前提:input 必须是 list
if len(input) == 1:
...
elif len(input) == 2:
...
else:
...
- 不能滥用 assert。很多情况下,程序中出现的不同情况都是意料之中的,需要我们用不同的方案去处理,这时候用条件语句进行判断更为合适。而对于程序中的一些 run-time error,请记得使用异常处理。
上下文管理器context manager和With语句
- 在任何一门编程语言中,文件的输入输出、数据库的连接断开等,都是很常见的资源管理操作。但资源都是有限的,在写程序时,我们必须保证这些资源在使用过后得到释放,不然就容易造成资源泄露,轻者使得系统处理缓慢,重则会使系统崩溃。
- 在 Python 中,对应的解决方式便是上下文管理器(context manager)。上下文管理器,能够帮助你自动分配并且释放资源,其中最典型的应用便是 with 语句。
for x in range(10000000):
with open('test.txt', 'w') as f:
f.write('hello')
基于类的上下文管理器
class FileManager:
def __init__(self, name, mode):
print('calling __init__ method')
self.name = name
self.mode = mode
self.file = None
# 返回需要被管理的资源
def __enter__(self):
print('calling __enter__ method')
self.file = open(self.name, self.mode)
return self.file
# 一些释放、清理资源的操作
# 方法“__exit__()”中的参数“exc_type, exc_val, exc_tb”,分别表示 exception_type、exception_value 和 traceback。当我们执行含有上下文管理器的 with 语句时,如果有异常抛出,异常的信息就会包含在这三个变量中,传入方法“__exit__()”。
def __exit__(self, exc_type, exc_val, exc_tb):
print('calling __exit__ method')
if self.file:
self.file.close()
with FileManager('test.txt', 'w') as f:
print('ready to write to file')
f.write('hello world')
## 输出
calling __init__ method
calling __enter__ method
ready to write to file
calling __exit__ method
基于生成器的上下文管理器
from contextlib import contextmanager
@contextmanager
def file_manager(name, mode):
try:
f = open(name, mode)
yield f
finally:
f.close()
with file_manager('test.txt', 'w') as f:
f.write('hello world')
- 基于类的上下文管理器更加 flexible,适用于大型的系统开发;
- 而基于生成器的上下文管理器更加方便、简洁,适用于中小型程序。
- 自行定义相关的操作对异常进行处理,而处理完异常后,也别忘了加上
“return True”
这条语句,否则仍然会抛出异常。
单元测试
pdb & cProfile:调试和性能分析
a = 1
b = 2
import pdb
pdb.set_trace()
c = 3
print(a + b + c)
- pdb自带的一个调试库。它为 Python 程序提供了交互式的源代码调试功能,是命令行版本的 IDE 断点调试器
- https://docs.python.org/3/library/pdb.html#module-pdb
- profile,是指对代码的每个部分进行动态的分析,比如准确计算出每个模块消耗的时间等。这样你就可以知道程序的瓶颈所在,从而对其进行修正或优化。
- pdb 为 Python 程序提供了一种通用的、交互式的高效率调试方案;而 cProfile 则是为开发者提供了每个代码块执行效率的详细分析,有助于我们对程序的优化与提高。
- https://docs.python.org/3.7/library/profile.html
来源:oschina
链接:https://my.oschina.net/u/4419233/blog/4817944