Python代码规范和命名规范

http://www.imooc.com/article/19184?block_id=tuijian_wz#child_5_1

Python代码规范和命名规范

前言

Python 学习之旅,先来看看 Python 的代码规范,让本身先有个意识,并且在日后的学习中慢慢养成习惯html

目录

Python代码规范

1、简明概述
一、编码
  • 如无特殊状况, 文件一概使用 UTF-8 编码
  • 如无特殊状况, 文件头部必须加入#-*-coding:utf-8-*-标识
二、代码格式

2.一、缩进

  • 统一使用 4 个空格进行缩进

2.二、行宽

每行代码尽可能不超过 80 个字符(在特殊状况下能够略微超过 80 ,但最长不得超过 120)python

理由:web

  • 这在查看 side-by-side 的 diff 时颇有帮助
  • 方便在控制台下查看代码
  • 太长多是设计有缺陷

2.三、引号

简单说,天然语言使用双引号,机器标示使用单引号,所以 代码里 多数应该使用 单引号正则表达式

  • 天然语言 使用双引号 "..."
    例如错误信息;不少状况仍是 unicode,使用u"你好世界"
  • 机器标识 使用单引号 '...'
    例如 dict 里的 key
  • 正则表达式 使用原生的双引号 r"..."
  • 文档字符串 (docstring) 使用三个双引号 """......"""

2.四、空行

  • 模块级函数和类定义之间空两行;
  • 类成员函数之间空一行;
     
     
     
     
  1. class A :
  2. def __init__ ( self ):
  3. pass
  4. def hello ( self ):
  5. pass
  6. def main ():
  7. pass
  • 可使用多个空行分隔多组相关的函数
  • 函数中可使用空行分隔出逻辑相关的代码

2.五、编码

  • 文件使用 UTF-8 编码
  • 文件头部加入#-*-conding:utf-8-*-标识
三、import 语句
  • import 语句应该分行书写
     
     
     
     
  1. # 正确的写法
  2. import os
  3. import sys
  4. # 不推荐的写法
  5. import sys , os
  6. # 正确的写法
  7. from subprocess import Popen , PIPE
  • import语句应该使用 absolute import
     
     
     
     
  1. # 正确的写法
  2. from foo . bar import Bar
  3. # 不推荐的写法
  4. from .. bar import Bar
  • import语句应该放在文件头部,置于模块说明及docstring以后,于全局变量以前;
  • import语句应该按照顺序排列,每组之间用一个空行分隔
     
     
     
     
  1. import os
  2. import sys
  3. import msgpack
  4. import zmq
  5. import foo
  • 导入其余模块的类定义时,可使用相对导入
     
     
     
     
from myclass import MyClass
  • 若是发生命名冲突,则可以使用命名空间
     
     
     
     
  1. import bar
  2. import foo . bar
  3. bar . Bar ()
  4. foo . bar . Bar ()
四、空格
  • 在二元运算符两边各空一格[=,-,+=,==,>,in,is not, and]:
     
     
     
     
  1. # 正确的写法
  2. i = i + 1
  3. submitted += 1
  4. x = x * 2 - 1
  5. hypot2 = x * x + y * y
  6. c = ( a + b ) * ( a - b )
  7. # 不推荐的写法
  8. i = i + 1
  9. submitted += 1
  10. x = x * 2 - 1
  11. hypot2 = x * x + y * y
  12. c = ( a + b ) * ( a - b )
  • 函数的参数列表中,,以后要有空格
     
     
     
     
  1. # 正确的写法
  2. def complex ( real , imag ):
  3. pass
  4. # 不推荐的写法
  5. def complex ( real , imag ):
  6. pass
  • 函数的参数列表中,默认值等号两边不要添加空格
     
     
     
     
  1. # 正确的写法
  2. def complex ( real , imag = 0.0 ):
  3. pass
  4. # 不推荐的写法
  5. def complex ( real , imag = 0.0 ):
  6. pass
  • 左括号以后,右括号以前不要加多余的空格
     
     
     
     
  1. # 正确的写法
  2. spam ( ham [ 1 ], { eggs : 2 })
  3. # 不推荐的写法
  4. spam ( ham [ 1 ], { eggs : 2 } )
  • 字典对象的左括号以前不要多余的空格
     
     
     
     
  1. # 正确的写法
  2. dict [ 'key' ] = list [ index ]
  3. # 不推荐的写法
  4. dict [ 'key' ] = list [ index ]
  • 不要为对齐赋值语句而使用的额外空格
     
     
     
     
  1. # 正确的写法
  2. x = 1
  3. y = 2
  4. long_variable = 3
  5. # 不推荐的写法
  6. x = 1
  7. y = 2
  8. long_variable = 3
五、换行

Python 支持括号内的换行。这时有两种状况。session

1) 第二行缩进到括号的起始处app

     
     
     
     
  1. foo = long_function_name ( var_one , var_two ,
  2. var_three , var_four )

2) 第二行缩进 4 个空格,适用于起始括号就换行的情形编辑器

     
     
     
     
  1. def long_function_name (
  2. var_one , var_two , var_three ,
  3. var_four ):
  4. print ( var_one )

使用反斜杠\换行,二元运算符+ .等应出如今行末;长字符串也能够用此法换行ide

     
     
     
     
  1. session . query ( MyTable ). \
  2. filter_by ( id = 1 ). \
  3. one ()
  4. print 'Hello, ' \
  5. '%s %s!' % \
  6. ( 'Harry' , 'Potter' )

禁止复合语句,即一行中包含多个语句:svg

     
     
     
     
  1. # 正确的写法
  2. do_first ()
  3. do_second ()
  4. do_third ()
  5. # 不推荐的写法
  6. do_first (); do_second (); do_third ();

if/for/while必定要换行:函数

     
     
     
     
  1. # 正确的写法
  2. if foo == 'blah' :
  3. do_blah_thing ()
  4. # 不推荐的写法
  5. if foo == 'blah' : do_blash_thing ()
六、docstring

docstring 的规范中最其本的两点:

  1. 全部的公共模块、函数、类、方法,都应该写 docstring 。私有方法不必定须要,但应该在 def 后提供一个块注释来讲明。
  2. docstring 的结束”“”应该独占一行,除非此 docstring 只有一行。
     
     
     
     
  1. """Return a foobar
  2. Optional plotz says to frobnicate the bizbaz first.
  3. """
  4. """Oneline docstring"""
2、注释
一、注释

1.一、块注释

“#”号后空一格,段落件用空行分开(一样须要“#”号)

     
     
     
     
  1. # 块注释
  2. # 块注释
  3. #
  4. # 块注释
  5. # 块注释

1.二、行注释

至少使用两个空格和语句分开,注意不要使用无心义的注释

     
     
     
     
  1. # 正确的写法
  2. x = x + 1 # 边框加粗一个像素
  3. # 不推荐的写法(无心义的注释)
  4. x = x + 1 # x加1

1.三、建议

  • 在代码的关键部分(或比较复杂的地方), 能写注释的要尽可能写注释

  • 比较重要的注释段, 使用多个等号隔开, 能够更加醒目, 突出重要性
     
     
     
     
  1. app = create_app ( name , options )
  2. # =====================================
  3. # 请勿在此处添加 get post等app路由行为 !!!
  4. # =====================================
  5. if __name__ == '__main__' :
  6. app . run ()
二、文档注释(Docstring)

做为文档的Docstring通常出如今模块头部、函数和类的头部,这样在python中能够经过对象的__doc__对象获取文档.
编辑器和IDE也能够根据Docstring给出自动提示.

  • 文档注释以 “”” 开头和结尾, 首行不换行, 若有多行, 末行必需换行, 如下是Google的docstring风格示例
     
     
     
     
  1. # -*- coding: utf-8 -*-
  2. """Example docstrings.
  3. This module demonstrates documentation as specified by the `Google Python
  4. Style Guide`_. Docstrings may extend over multiple lines. Sections are created
  5. with a section header and a colon followed by a block of indented text.
  6. Example:
  7. Examples can be given using either the ``Example`` or ``Examples``
  8. sections. Sections support any reStructuredText formatting, including
  9. literal blocks::
  10. $ python example_google.py
  11. Section breaks are created by resuming unindented text. Section breaks
  12. are also implicitly created anytime a new section starts.
  13. """
  • 不要在文档注释复制函数定义原型, 而是具体描述其具体内容, 解释具体参数和返回值等
     
     
     
     
  1. # 不推荐的写法(不要写函数原型等废话)
  2. def function ( a , b ):
  3. """function(a, b) -> list"""
  4. ... ...
  5. # 正确的写法
  6. def function ( a , b ):
  7. """计算并返回a到b范围内数据的平均值"""
  8. ... ...
  • 对函数参数、返回值等的说明采用numpy标准, 以下所示
     
     
     
     
  1. def func ( arg1 , arg2 ):
  2. """在这里写函数的一句话总结(如: 计算平均值).
  3. 这里是具体描述.
  4. 参数
  5. ----------
  6. arg1 : int
  7. arg1的具体描述
  8. arg2 : int
  9. arg2的具体描述
  10. 返回值
  11. -------
  12. int
  13. 返回值的具体描述
  14. 参看
  15. --------
  16. otherfunc : 其它关联函数等...
  17. 示例
  18. --------
  19. 示例使用doctest格式, 在`>>>`后的代码能够被文档测试工具做为测试用例自动运行
  20. >>> a=[1,2,3]
  21. >>> print [x + 3 for x in a]
  22. [4, 5, 6]
  23. """
  • 文档注释不限于中英文, 但不要中英文混用

  • 文档注释不是越长越好, 一般一两句话能把状况说清楚便可

  • 模块、公有类、公有方法, 能写文档注释的, 应该尽可能写文档注释
3、命名规范
一、模块
  • 模块尽可能使用小写命名,首字母保持小写,尽可能不要用下划线(除非多个单词,且数量很少的状况)
     
     
     
     
  1. # 正确的模块名
  2. import decoder
  3. import html_parser
  4. # 不推荐的模块名
  5. import Decoder
二、类名
  • 类名使用驼峰(CamelCase)命名风格,首字母大写,私有类可用一个下划线开头
     
     
     
     
  1. class Farm ():
  2. pass
  3. class AnimalFarm ( Farm ):
  4. pass
  5. class _PrivateFarm ( Farm ):
  6. pass
  • 将相关的类和顶级函数放在同一个模块里. 不像Java, 不必限制一个类一个模块.
三、函数
  • 函数名一概小写,若有多个单词,用下划线隔开
     
     
     
     
  1. def run ():
  2. pass
  3. def run_with_env ():
  4. pass
  • 私有函数在函数前加一个下划线_
     
     
     
     
  1. class Person ():
  2. def _private_func ():
  3. pass
四、变量名
  • 变量名尽可能小写, 若有多个单词,用下划线隔开
     
     
     
     
  1. if __name__ == '__main__' :
  2. count = 0
  3. school_name = ''
  • 常量采用全大写,若有多个单词,使用下划线隔开
     
     
     
     
  1. MAX_CLIENT = 100
  2. MAX_CONNECTION = 1000
  3. CONNECTION_TIMEOUT = 600
五、常量
  • 常量使用如下划线分隔的大写命名
     
     
     
     
  1. MAX_OVERFLOW = 100
  2. Class FooBar :
  3. def foo_bar ( self , print_ ):
  4. print ( print_ )
</div>
            </div>
        </article>
相关文章
相关标签/搜索