最近在学习《编写高质量代码-改善python程序的91个建议》,记录下读书笔记
使用版本:Python 3.4.0
系统:Windows7
1.字符串格式化:
1 def show(name,age,email): 2 #普通方法 3 print(‘your name is: %s \nyour age is: %i \nyour email is: %s‘ %(name,age,email)) 4 #更加清晰引用的方法 5 print(‘your name is: %(name)s \n your age is: %(age)i \nyour email is: %(email)s‘ %{‘name‘:name,‘age‘:age,‘email‘:email}) 6 #str.format()字符串格式化方法 7 print(‘your name is: {name} \nyour age is {age} \nyour email is: {email}‘.format(name = name,age = age,email = email)) 8 9 if __name__ == ‘__main__‘: 10 show(‘wwl‘,24,‘[email protected]‘)
2.包管理器:Pip
官网: https://pip.pypa.io/en/latest/ Python 3.4版本内置了pip 存放在python安装路径的Scripts目录,只需要把这个路径加到系统的path路径即可。安装包:pip install SomePackage卸载包:pip uninstall SomePackage升级包:pip install --upgrade SomePackage显示安装包:pip list显示安装包哪些需要升级:pip list --outdated显示包信息:pip show SomePackage显示安装包包含哪些文件:pip show --files SomePackage
$ pip install SomePackage # latest version $ pip install SomePackage==1.0.4 # specific version $ pip install ‘SomePackage>=1.0.4‘ # minimum version
Stackoverflow上面关于pip的讨论: http://stackoverflow.com/questions/4750806/how-to-install-pip-on-windows/ http://stackoverflow.com/questions/2436731/does-python-have-a-package-module-management-system/13445719 http://stackoverflow.com/questions/3220404/why-use-pip-over-easy-install
3.代码分析工具
pylint官网: http://pylint.org/ Pylint 默认使用的代码风格是 PEP 8
4.三元操作
C ? X: Y 当C为True的时候取值X,否则取值Y Python等价形式 X if C else Y >>> a = 3 >>> print(‘haha‘) if a <5 else ‘hehe‘ haha >>> print(‘haha‘) if a <2 else ‘hehe‘ ‘hehe‘
5.switch..case
Python中没有switch...case... 以下两种方法代替: 1.if...elif... if x == 0: return(‘000‘) elif x == 1: return(‘1111‘) 2.{}.get(x) {0:‘000‘,1:‘1111‘}.get(0)
6.断言assert
>>> x = 1 >>> y = 2 >>> assert x == y,‘not equals‘ Traceback (most recent call last): File "<pyshell#2>", line 1, in <module> assert x == y,‘not equals‘ AssertionError: not equals 等价于下面 >>> if __debug__ and not x == y: raise AssertionError(‘not equals‘) Traceback (most recent call last): File "<pyshell#13>", line 2, in <module> raise AssertionError(‘not equals‘) AssertionError: not equals 其中__debug__为True而且不能修改使用断言是有代价的,它会对性能产生一定影响。禁用断言的方法是在运行脚本时候加上-O(忽略与断言相关的语句)断言是被设计用来捕获用户定义的约束的,而不是用来捕获程序本身错误
7.数值交换不推荐中间值
常用方法: temp = x x = y y = temp 推荐方法: x,y = y,x 解析: 先计算=右边的值为(y,x)然后分别赋值给x,y变量 性能对比: >>> import timeit >>> timeit.Timer(‘x,y = y,x‘,‘x = 1;y = 2‘).timeit() 0.03071109231768787 >>> timeit.Timer(‘temp = x;x = y;y = temp‘,‘x = 1;y = 2‘).timeit() 0.035570626849676046
8.惰性计算lazy evaluayion
if x and y 在x为False的时候y不再计算 if x or y 在x为True的时候y不再计算 x和y表达式的前后顺序会对程序执行时间造成影响。
9.枚举enum
Enums have been added to Python 3.4 as described in PEP 435. It has also been backported to 3.3, 3.2, 3.1, 2.7, 2.6, 2.5, and 2.4 on pypi. To use backports, do $ pip install enum34, installing enum (no numbers) will install a completely different and incompatible version. from enum import Enum Animal = Enum(‘Animal‘, ‘ant bee cat dog‘) 等价于 class Animals(Enum): ant = 1 bee = 2 cat = 3 dog = 4 以上是下面链接的搬运: http://stackoverflow.com/questions/36932/how-can-i-represent-an-enum-in-python
10.类型检查推荐isinstance而不是type
对应内建的基本类型来说使用type()进行类型检查是ok的; 基于内建类型扩展的用户自定义类型,type并不能准确返回结果;
>>> import types
>>> class UserInt(int):
def __init__(self,val=0):
self._val = int(val)
>>> n = UserInt(2)
>>> n
2
>>> type(n)
<class ‘__main__.UserInt‘>
>>> isinstance(n,int)
True
关于type() 2.7和3.4对于class的处理还是有区别的,如下图:
时间: 2024-10-19 12:33:54