赞
踩
本篇文章给大家谈谈python代码怎么写的整洁,以及python代码在哪儿写,希望对各位有所帮助,不要忘了收藏本站喔。
Python 学习之旅,先来看看 Python 的代码规范,让自己先有个意识,而且在往后的学习中慢慢养成习惯
Python代码规范
如无特殊情况, 文件一律使用 UTF-8 编码
如无特殊情况, 文件头部必须加入#-*-coding:utf-8-*-
标识
统一使用 4 个空格进行缩进
每行代码尽量不超过 80 个字符(在特殊情况下可以略微超过 80 ,但最长不得超过 120)
理由:
这在查看 side-by-side 的 diff 时很有帮助
方便在控制台下查看代码
太长可能是设计有缺陷
简单说,自然语言使用双引号,机器标示使用单引号,因此 代码里 多数应该使用 单引号
自然语言 使用双引号 "..."
例如错误信息;很多情况还是 unicode,使用u"你好世界"
机器标识 使用单引号 "..."
例如 dict 里的 key
正则表达式 使用原生的双引号 r"..."
文档字符串 (docstring) 使用三个双引号 """......"""
模块级函数和类定义之间空两行;
类成员函数之间空一行;
class A: def __init__(self): pass def hello(self): passdef main(): pass
可以使用多个空行分隔多组相关的函数
函数中可以使用空行分隔出逻辑相关的代码
文件使用 UTF-8 编码
文件头部加入#-*-conding:utf-8-*-
标识
import 语句应该分行书写
# 正确的写法import osimport sys# 不推荐的写法import sys,os# 正确的写法from subprocess import Popen, PIPE复制代码import语句应该使用 absolute import# 正确的写法from foo.bar import Bar# 不推荐的写法from ..bar import Bar
import语句应该放在文件头部,置于模块说明及docstring之后,于全局变量之前;
import语句应该按照顺序排列,每组之间用一个空行分隔
import osimport sysimport msgpackimport zmqimport foo
from myclass import MyClass
import barimport foo.barbar.Bar()foo.bar.Bar()
[=,-,+=,==,>,in,is not, and]
:# 正确的写法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 支持括号内的换行。这时有两种情况不会c语言可以学python吗。
1) 第二行缩进到括号的起始处
foo = long_function_name(var_one, var_two, var_three, var_four)
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()
"""Return a foobarOptional plotz says to frobnicate the bizbaz first.""""""Oneline docstring"""
“#”号后空一格,段落件用空行分开(同样需要“#”号)
# 块注释# 块注释## 块注释# 块注释
至少使用两个空格和语句分开,注意不要使用无意义的注释
# 正确的写法x = x + 1 # 边框加粗一个像素# 不推荐的写法(无意义的注释)x = x + 1 # x加1
app = create_app(name, options)# =====================================# 请勿在此处添加 get post等app路由行为 !!!# =====================================if __name__ == "__main__": app.run()
# -*- 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] """
# 正确的模块名import decoderimport html_parser# 不推荐的模块名import Decoder
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_)
——End——
赞
踩
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。