Python的pep8-代码规范
1、 代码布局设计
1.1 缩进
A、 使用四个空格来进行缩进
B、 换行的时候可以使用反斜杠,最好的方法是使用园括号,在使用反斜杠的时候,在反斜杠的后直接回车,不能有任何空格存在
比较好的做法如下:
对准开始的分隔符:
# Aligned with opening delimiter. foo = long_function_name(var_one, var_two, var_three, var_four) |
包含更多的缩进表示是剩余部分:
# More indentation included to distinguish this from the rest. def long_function_name( var_one, var_two, var_three, var_four): print(var_one) |
悬挂缩进应该添加一个级别:
# Hanging indents should add a level. foo = long_function_name( var_one, var_two, var_three, var_four) |
比较差的做法如下:(代码同样是可以运行的)
# Arguments on first line forbidden when not using vertical alignment.—未使用垂直对齐 foo = long_function_name(var_one, var_two, var_three, var_four) # Further indentation required as indentation is not distinguishable.(未使用缩进来表示每一层级) def long_function_name( var_one, var_two, var_three, var_four): print(var_one)
|
对于续行来说,四个空格的缩进是可选的。
可选的如下:
# Hanging indents *may* be indented to other than 4 spaces.悬挂缩进的时候可以不是四个空格 foo = long_function_name( var_one, var_two, var_three, var_four)
|
当使用if语句的时候,如果条件恰好的缩进为四个空格空格,那么导致后面的语句的缩进也是四个空格,那么这种情况下是可以接受的,如下所示:
没有额外的缩进:
# No extra indentation. if (this_is_one_thing and that_is_another_thing): do_something() |
添加一个注释来进行分割缩进,做到语法高亮显示:
# Add a comment, which will provide some distinction in editors # supporting syntax highlighting. if (this_is_one_thing and that_is_another_thing): # Since both conditions are true, we can frobnicate. do_something() |
在续行中添加额外的缩进:
# Add some extra indentation on the conditional continuation line. if (this_is_one_thing and that_is_another_thing): do_something()
|
成对的小括号,中括号在多行的结构中可以写成多行,然后括号在第一个不为空白的位置结束。如下:
my |