1. 行长与换行
为了增强可读性,建议代码每行长度不超过80个字符,import和comment除外;
虽然反斜杠\可以把不同的行内容连接起来,但是仍然不建议使用。实际上,Python中规定圆括号、方括号和花括号可以跨越多个自然行,我们可以利用这个规则规避反斜杠;
Expressions in parentheses, square brackets or curly braces can be split over more than one physical line without using backslashes.
# Example 1 content = ('I want say something directly.' 'But it is too long!') print (content) def IsTime(year = 1900, month = 1, day = 1, hour = 0, minute = 0, second = 0): if (1900 < year < 2100 and 1 <= month <= 12 and 1 <= day <= 31 and 0 <= hour < 24 and 0 <= minute < 60 and 0 <= second < 60): return 1
2. 括号
上一个Item谈到括号可以进行自然行的连接,但是请不要强行在条件或者返回语句中使用括号,即便语义上没有问题,如:
# Example 2 if (year == 1990): print("90's")
3. 缩进
请不要使用在Python代码中使用<tab>,不仅仅是因为Indent会导致语法错误,甚至说在某些编辑器里面,当tab现实的长度不与你认为的4 space对等时,会出现无法预料的结果;
另外,对于换行的语句,请做到悬挂式缩进,如Example 1中所示。
4. 空行
为了增加代码的可读性,建议使用空行来区分不同的定义。
# Example 3 class ExampleClass(object): publicValue = 1 _privateValue = 0 def __init__(self, pub, pri): publicValue = pub _privateValue = pri def getPublic(self): return publicValue def getPrivate(self): return privateValue
5. 空格
主要注意几点:
- 在语法分隔符后面加空格,行末除外
- 在运算符两端加空格,参数值除外
- 紧邻括号不应空格
- 不要用空格对齐注释,注重美观会导致极大的维护成本
#Example 4 dict['key'] = list[idx] # not dict [ 'key' ] = list [ idx ] spam(1) # not spam (1) def complex(real, imag=0.0): return magic(r=real, i=imag) # not def complex(real, imag= 0.0): return magic(r = real, i = imag)
6. #!
主要在直接运行的Python文件头部声明文件信息:
#!/usr/bin/python2 #!coding : utf8
7. 注释
请多多使用注释,利好你的合作伙伴和以后的你。
8. 类
对于没有任何基类的类来说,从object显示继承可以使你的类实现系统默认一些语义而不受兼容性的影响。
9. 字符串
在Python里面,字符串是一个不可以写的内建对象,因而我们在以下几种情况下加法运算,否则使用其他方案来进行代替:
# Example 5 x = a + b # not x = '%s%s' (a, B)/> or x = '{}{}'.format(a, B)/> #otherwise x = '%s is not in %s' % (a, B)/> x = '{} is not in {}'.format(a, B)/> arr = [] for r in rows: arr.append(r['title']) titles = ','.join(arr) ''' not use like this: titles = "" count = 0 for r in rows: if count = 0: titles = r['title'] else: titles += ',' + r['title'] '''
10. FD(File Description)
在使用到系统资源时,请显示的释放。建议在使用到系统资源的时候,使用with来进行自动管理。with语句实际上是一个外覆器,实现了一个try...except...finally的过程。
- with的内容获取内容管理器
- 加载__exit__()函数
- 调用__enter__()函数
- 如果说with后面有as语句,那么把返回值传递给as指向的target
- 执行语句
- 执行__exit__()函数
- finally`负责资源释放
标志未来需要添加或者修改的代码注释非常必要。
12. import
请给每个导入的模块一个单独行,不要吝啬
13. 封装
请尽量使用接口和私有变量来控制你模块中的类
14. 使用if __name__ == '__main__'
将程序的入口放在一个函数中,防止模块中的代码被执行。
# Example 6 def main(): ... if __name__ == '__main__': main()