本文共 5372 字,大约阅读时间需要 17 分钟。
程序不仅仅是给机器看的,自己在回顾的时候也会查看。如果在团队开发中,规范的编程习惯以及优良的注释会大大地提高团队的开发效率。现在来看看Python中有哪些编程规范。
无特殊情况,建议Python脚本程序一律使用 UTF-8 编码,并且在文件头部必须加入#-*-coding:utf-8-*-
标识,声明文件编码方式,程序文件编码要和声明编码保持一致。
缩进: 统一使用 4 个空格进行缩进。(默认一个tab键就是4个空格,有时程序格式问题可能出现在这里,tab键不一定就是4个空格)
行宽: 每行代码尽量不超过 80 个字符(在特殊情况下可以略微超过 80 ,但最长不得超过 120)。如果代码过长,说明代码设计方面可能不合理。除此之外也方便在控制台查看代码(linux)以及通过对side-by-side的diff时有帮助。
引号:自然语言,也就是说一般使用双引号;机器标示使用单引号,例如字典中的key,正则表达式使用原生的双引号 r"..."
;文档字符串 (docstring) 使用三个双引号 """ ......"""
。当然实际中需要灵活运用,毕竟三种引号使用是有区别的。
空行:
如下代码:
class A:# one line def __init__(self): pass# one line def hello(self): pass# one line# one linedef main(): pass
# 正确的写法import osimport sys# 不推荐的写法import sys,os# 正确的写法from subprocess import Popen, PIPE
# 正确的写法from foo.bar import Bar# 不推荐的写法from ..bar import Bar
from myclass import MyClass
import barimport foo.barbar.Bar()foo.bar.Bar()
# 正确的写法i = i + 1submitted += 1x = x * 2 - 1hypot2 = x * x + y * yc = (a + b) * (a - b)# 不推荐的写法i=i+1submitted +=1x = x*2 - 1hypot2 = x*x + y*yc = (a+b) * (a-b)
,
之后要有空格# 正确的写法def complex(real, imag): pass# 不推荐的写法def complex(real,imag): pass
# 正确的写法def complex(real, imag=0.0): pass# 不推荐的写法def complex(real, imag = 0.0): pass
# 正确的写法spam(ham[1], { eggs: 2})# 不推荐的写法spam( ham[1], { eggs : 2 } )
# 正确的写法dict['key'] = list[index]# 不推荐的写法dict ['key'] = list [index]
# 正确的写法x = 1y = 2long_variable = 3# 不推荐的写法x = 1y = 2long_variable = 3
Python 支持括号内的换行。这时有两种情况,如下:
foo = long_function_name(var_one, var_two, var_three, var_four)
def long_function_name( var_one, var_two, var_three, var_four): print(var_one)
使用反斜杠\
换行。 二元运算符+
、.
等应出现在行末;长字符串也可以用此法换行
session.query(MyTable).\ filter_by(id=1).\ one()print 'Hello, '\ '%s %s!' %\ ('Harry', 'Potter')
禁止复合语句。 即一行中包含多个语句:
# 正确的写法do_first()do_second()do_third()# 不推荐的写法do_first();do_second();do_third();
if/for/while
要换行。
# 正确的写法if foo == 'blah': do_blah_thing()# 不推荐的写法if foo == 'blah': do_blash_thing()
docstrings,文档注释,用于解释文档程序,帮助你的程序文档更加简单易懂。docstring 的规范中最其本的两点:
"""Return a foobarOptional plotz says to frobnicate the bizbaz first.""""""Oneline docstring"""
补充: 作为文档的Docstring一般出现在模块头部、函数和类的头部,这样在python中可以通过对象的__doc__
对象获取文档. 编辑器和IDE也可以根据Docstring给出自动提示
"""
开头和结尾, 首行不换行, 如有多行, 末行必需换行, 以下是Google的docstring风格示例# -*- coding: utf-8 -*-"""Example docstrings.This module demonstrates documentation as specified by the `Google PythonStyle Guide`_. Docstrings may extend over multiple lines. Sections are createdwith a section header and a colon followed by a block of indented text.Example: Examples can be given using either the ``Example`` or ``Examples`` sections. Sections support any reStructuredText formatting, including literal blocks:: $ python example_google.pySection breaks are created by resuming unindented text. Section breaksare also implicitly created anytime a new section starts."""
# 不推荐的写法(不要写函数原型等废话)def function(a, b): """function(a, b) -> list""" ... ...# 正确的写法def function(a, b): """计算并返回a到b范围内数据的平均值""" ... ...
def func(arg1, arg2): """在这里写函数的一句话总结(如: 计算平均值). 这里是具体描述. 参数 ---------- arg1 : int arg1的具体描述 arg2 : int arg2的具体描述 返回值 ------- int 返回值的具体描述 参看 -------- otherfunc : 其它关联函数等... 示例 -------- 示例使用doctest格式, 在`>>>`后的代码可以被文档测试工具作为测试用例自动运行 >>> a=[1,2,3] >>> print [x + 3 for x in a] [4, 5, 6] """
块注释 :“#”号后空一格,段落件用空行分开(同样需要“#”号)
# 块注释## 块注释
行注释: 至少使用两个空格和语句分开,不要使用无意义的注释
# 正确的写法x = x + 1 # 边框加粗一个像素# 不推荐的写法(无意义的注释)x = x + 1 # x加1
补充: 在代码的关键部分(或比较复杂的地方), 能写注释的要尽量写注释;比较重要的注释段, 使用多个等号隔开, 可以更加醒目, 突出重要性。
app = create_app(name, options)# =====================================# 请勿在此处添加 get post等app路由行为 !!!# =====================================if __name__ == '__main__': app.run()
模块: 模块尽量使用小写命名,首字母保持小写,尽量不要用下划线(除非多个单词,且数量不多的情况)
# 正确的模块名import decoderimport html_parser# 不推荐的模块名import Decoder
类名: 类名使用驼峰(CamelCase)命名风格,首字母大写,私有类可用一个下划线开头;将相关的类和顶级函数放在同一个模块里. 不像Java, 没必要限制一个类一个模块。
class Farm(): passclass AnimalFarm(Farm): passclass _PrivateFarm(Farm): pass
函数:
def run(): passdef run_with_env(): pass
_
class Person(): def _private_func(): pass
变量名
if __name__ == '__main__': count = 0 school_name = ''
MAX_CLIENT = 100MAX_CONNECTION = 1000CONNECTION_TIMEOUT = 600
常量 :使用以下划线分隔的大写命名。
MAX_OVERFLOW = 100Class FooBar: def foo_bar(self, print_): print(print_)
现在一般的编辑器和IDE都会有格式提醒,python的代码错误检查通常用pep8、pylint和flake8规范,这些规范对代码格式要求也不同,掌握以上的规范也大致差不多了,也可以安装pep8、pylint或flake8相关包,编程时会有相对的提醒,辅助我们的编程!
转载地址:http://bmlxf.baihongyu.com/