文档详情

Python-编码规范汇编.docx

发布:2018-05-17约4.47千字共7页下载文档
文本预览下载声明
Python 编码规范遵循良好的编码风格,可以有效的提高代码的可读性,降低出错几率和维护难度。在团队开发中,使用(尽量)统一的编码风格,还可以降低沟通成本。网上有很多版本的编码规范,基本上都是遵循 PEP8 的规范:PEP 0008 – Style Guide for Python CodeGoogle 的 Python 风格指南Python Guide - Code StylePocoo Styleguide除了在编码时主动遵循规范,还有很多有用的工具:IntelliJ IDEA 和 PyCharm 的格式化代码功能Google 开源的 Python 文件格式化工具:/google/yapfpyflakes, pylint 等工具及各种编辑器的插件本文的内容主要摘自互联网上各种版本的规范,因为公司有些小伙伴代码风格不太好,所以整理了一份算是团队的编码规范。缩进不要使用 tab 缩进使用任何编辑器写 Python,请把一个 tab 展开为 4 个空格绝对不要混用 tab 和空格,否则容易出现?IndentationError空格在 list, dict, tuple, set, 参数列表的?,?后面加一个空格在 dict 的?:?后面加一个空格在注释符号?#?后面加一个空格,但是?#!/usr/bin/python?的?#?后不能有空格操作符两端加一个空格,如?+,?-,?*,?/,?|,?,?=接上一条,在参数列表里的?=?两端不需要空格括号((),?{},?[])内的两端不需要空格空行function 和 class 顶上两个空行class 的 method 之间一个空行函数内逻辑无关的段落之间空一行,不要过度使用空行不要把多个语句写在一行,然后用?;?隔开if/for/while 语句中,即使执行语句只有一句,也要另起一行换行每一行代码控制在 80 字符以内使用?\?或?()?控制换行,举例:deffoo(first, second, third, fourth, fifth, sixth, and_some_other_very_long_param): user = User.objects.filter_by(first=first, second=second, third=third) \ .skip(100).limit(100) \ .all()text = (Long strings can be made up of several shorter strings.)命名使用有意义的,英文单词或词组,绝对不要使用汉语拼音package/module 名中不要出现?-各种类型的命名规范:TypePublicInternalModuleslower_with_under_lower_with_underPackageslower_with_under?ClassesCapWords_CapWordsExceptionsCapWords?Functionslower_with_under()_lower_with_under()Global/Class ConstantsCAPS_WITH_UNDER_CAPS_WITH_UNDERGlobal/Class Variableslower_with_under_lower_with_underInstance Variableslower_with_under_lower_with_under?(protected) or?__lower_with_under?(private)Method Nameslower_with_under()_lower_with_under()?(protected) or?__lower_with_under()?(private)Function/Method Parameterslower_with_under?Local Variableslower_with_under?import所有 import 尽量放在文件开头,在 docstring 下面,其他变量定义的上面不要使用?from foo imort *import 需要分组,每组之间一个空行,每个分组内的顺序尽量采用字典序,分组顺序是:标准库第三方库本项目的 package 和 module不要使用隐式的相对导入(implicit relative imports),可是使用显示的相对导入(explicit relative imports),如?from ..utils import validator,最好使用全路径导入(absolute imports)对于不同的 package,一个 import 单独一行,
显示全部
相似文档