Python 代码规范

发布时间:2020-07-22 20:05:08 作者:wzlinux
来源:网络 阅读:1436

前言

Python 学习之旅,先来看看 Python 的代码规范,让自己先有个意识,而且在往后的学习中慢慢养成习惯。

目录

Python 代码规范

一、简要概述

1、编码

2、代码格式

2.1、缩进

2.2、行宽

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

理由:

2.3、引号

简单说,自然语言使用双引号,机器标示使用单引号,因此代码里多数应该使用单引号

2.4、空行

class A:

    def __init__(self):
        pass

    def hello(self):
        pass

def main():
    pass 

可以使用多个空行分隔多组相关的函数
函数中可以使用空行分隔出逻辑相关的代码

3、import 语句

# 正确的写法
import os
import sys

# 不推荐的写法
import sys,os

# 正确的写法
from subprocess import Popen, PIPE
# 正确的写法
from foo.bar import Bar

# 不推荐的写法
from ..bar import Bar
import os
import sys

import msgpack
import zmq

import foo
from myclass import MyClass
import bar
import foo.bar

bar.Bar()
foo.bar.Bar()

4、空格

# 正确的写法
i = i + 1
submitted += 1
x = x * 2 - 1
hypot2 = x * x + y * y
c = (a + b) * (a - b)

# 不推荐的写法
i=i+1
submitted +=1
x = x*2 - 1
hypot2 = x*x + y*y
c = (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 = 1
y = 2
long_variable = 3

# 不推荐的写法
x             = 1
y             = 2
long_variable = 3

5、换行

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

5.1、第二行缩进到括号的起始处

foo = long_function_name(var_one, var_two,
                         var_three, var_four)

5.2、第二行缩进 4 个空格,适用于起始括号就换行的情形

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()

6、docstring

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

"""Return a foobar
Optional plotz says to frobnicate the bizbaz first.
"""

"""Oneline docstring"""

二、注释

1、注释

1.1、块注释

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

# 块注释
# 块注释
#
# 块注释
# 块注释

1.2、行注释

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

# 正确的写法
x = x + 1  # 边框加粗一个像素

# 不推荐的写法(无意义的注释)
x = x + 1 # x加1

1.3、建议

在代码的关键部分(或比较复杂的地方), 能写注释的要尽量写注释
比较重要的注释段, 使用多个等号隔开, 可以更加醒目, 突出重要性

app = create_app(name, options)

# =====================================
# 请勿在此处添加 get post等app路由行为 !!!
# =====================================

if __name__ == '__main__':
    app.run()       

2、文档注释(Docstring)

作为文档的Docstring一般出现在模块头部、函数和类的头部,这样在python中可以通过对象的doc对象获取文档.
编辑器和IDE也可以根据Docstring给出自动提示.

# -*- coding: utf-8 -*-
"""Example docstrings.

This module demonstrates documentation as specified by the `Google Python
Style Guide`_. Docstrings may extend over multiple lines. Sections are created
with 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.py

Section breaks are created by resuming unindented text. Section breaks
are 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]
    """

文档注释不限于中英文, 但不要中英文混用
文档注释不是越长越好, 通常一两句话能把情况说清楚即可
模块、公有类、公有方法, 能写文档注释的, 应该尽量写文档注释

参考文档:https://www.python.org/dev/peps/pep-0008/
参考文档:https://zh-google-styleguide.readthedocs.io/en/latest/google-python-styleguide/python_style_rules

推荐阅读:
  1. python基础_注释&代码规范
  2. Python中递归是什么

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

python 代码规范

上一篇:王家林的第一个中国梦:免费为全社会培养100万名优秀的大数据从业人员!

下一篇:jquery常用代码--(一)

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》