【Python技巧】Python代码格式规范

PEP 8 -- Style Guide for Python Code

  1. 每个缩进固定为四个空格(一个tab)注意全篇应统一使用tab或者是空格

  2. 控制最大字符,每行最多79字符。对于没有分割的过长的文本,应限制在每行72字符

  3. 每行名字过长时,格式为:

# (1)将第二行变量与第一行对齐
foo = long_function_name(var_one, var_two,
                         var_three, var_four)

# (2)如果第一行写不下,将函数中的变量换行
def long_function_name(
        var_one, var_two, var_three,
        var_four):
    print(var_one)

# 调用时,也注意换行
foo = long_function_name(
    var_one, var_two,
    var_three, var_four)
  1. if语句过长时,格式为:
if (this_is_one_thing and
    that_is_another_thing):
    do_something()

# 另一种写法,如果and也换行,注意缩进
if (this_is_one_thing
        and that_is_another_thing):
    do_something()

5.列表的生成:

my_list = [
    1, 2, 3,
    4, 5, 6,
    ]
result = some_function_that_takes_arguments(
    'a', 'b', 'c',
    'd', 'e', 'f',
    )

6.计算符号的位置:应该位于每行行首

income = (gross_wages
          + taxable_interest
          + (dividends - qualified_dividends)
          - ira_deduction
          - student_loan_interest)

7.空行

Surround top-level function and class definitions with two blank lines.
顶层函数和类的定义前,加两行空格

Method definitions inside a class are surrounded by a single blank line.
在类内定义方法时,加一行空格

Use blank lines in functions, sparingly, to indicate logical sections.
在函数中使用空格来表示出逻辑

8.空格

(1) 括号后不要跟空格。

Yes: spam(ham[1], {eggs: 2})
No:  spam( ham[ 1 ], { eggs: 2 } )

(2)逗号和括号之间不要加空格

Yes: foo = (0,)
No:  bar = (0, )

(3)逗号后加空格,逗号前不加

Yes: if x == 4: print x, y; x, y = y, x
No:  if x == 4 : print x , y ; x , y = y , x

(4)冒号:数字与冒号之间不加,但如果是函数、其他运算符等有优先级关系的运算之间的冒号要加空格

ham[1:9], ham[1:9:3], ham[:9:3], ham[1::3], ham[1:9:]
ham[lower:upper], ham[lower:upper:], ham[lower::step]
ham[lower+offset : upper+offset]
ham[: upper_fn(x) : step_fn(x)], ham[:: step_fn(x)]
ham[lower + offset : upper + offset]

你可能感兴趣的:(【Python技巧】Python代码格式规范)