挂行缩进
- 如果语句下面没有缩进语句,一个tab即可;
- 如果下面还有缩进语句,为了区分,应该进一步缩进;
foo = long_function_name(var_one, var_two,
var_three, var_four)
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)
if (this_is_one_thing
and that_is_another_thing):
do_something()
my_list = [
1, 2, 3,
4, 5, 6,
7, 8, 9
]
result = some_function_that_takes_arguments(
"a", "b", "c",
"d", "e", "f"
)
- 在二远运算符之前中断
income = (gross_wages
+ taxable_interest
+ (dividends - qualified_dividends)
- ira_deduction
- student_loan_interest)
导入通常在分开的行
import os
import sys
from subprocess import Popen, PIPE1
加空格
- 目的: 是为了更好的阅读
- 如果使用具有不同优先级的运算符,请考虑在具有 最低优先级 的运算符周围添加空格
i = i + 1
submitted += 1
x = x*2 - 1
hypot2 = x*x + y*y
c = (a+b) * (a-b)
if x == 4: print x,y; x, y = y,x
spam([1], {eggs: 2})
- 切片: 单纯数字切片,不加空格; 扩张切片加两边空格; 省略参数,不加空格;
ham[lower:upper], ham[lower:upper:], ham[lower::step]
ham[lower+offset : upper+offset]
ham[: upper_fun(x) : step_fn(x)], ham[:: step_fn(x)]
dct['key'] = list[index]
- 在制定关键字参数或者默认参数值的时候,不要在=附近加上空格
def complex(real, imag=0.0):
return magic(r=real, i=imag)
- 功能型注释应该使用冒号的一般性规则,并且在使用->的时候要在两边加空格
def munge(input: AnyStr): ...
def munge() -> AnStr: ...
当代码更改时,优先更新对应的注释!
- 行内注释和代码至少要有两个空格分隔
x = x + 1 # Increment x1 (二加一)
- 多行文档说明使用的结尾三引号应该自成一行
"""函数或类功能说明
:param xxx: 参数说明
:param yyy: 参数说明
"""
def print_lines(char, times):
"""print multi_line
:param char: the charactor of split use
:param times: the times of charactor
"""
pass
类的参数
始终要将 self 作为实例方法的的第一个参数。
始终要将 cls 作为类静态方法的第一个参数。
如果函数的参数名和已有的关键词冲突,在最后加单一下划线比缩写或随意拼写更好。因此 class_ 比 clss 更好。(也许最好用同义词来避免这种冲突)
def class_(): ...
常量
- 常量: 通过 下划线分隔的全大写字母命名
MAX_COVERLOW = 66
TOTAL = 33
与单例对象的比较
和像None这样的单例对象进行比较的时候应该始终用 is 或者 is not,永远不要用等号运算符
if aa is None: ... if aa is not None: ...
函数定义
- 始终使用def表达式,而不是通过赋值语句将lambda表达式绑定到一个变量上。
Recommend:
def f(x): return 2*xx
Not recommend:
f = lambda x: 2*xx