Python常用PEP8编码规范和建议经验分享.docVIP

  • 8
  • 0
  • 约2.99千字
  • 约 8页
  • 2018-11-11 发布于江苏
  • 举报

Python常用PEP8编码规范和建议经验分享.doc

Python常用PEP8编码规范和建议经验分享

Python常用PEP8编码规范和建议经验分享   缩进   每级缩进用4个空格。   括号中使用垂直隐式缩进或使用悬挂缩进。   EXAMPLE: # (垂直隐式缩进)对准左括号 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)   # 右括号回退 my_list = [ 1, 2, 3, 4, 5, 6, ] result = some_funcTIon_that_takes_arguments( ‘a’, ‘b’, ‘c’, ‘d’, ‘e’, ‘f’, )   错误示范: # 不使用垂直对齐时,第一行不能有参数。 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)   # 右括号不回退,不推荐 my_list = [ 1, 2, 3, 4, 5, 6, ]   result = some_function_that_takes_arguments( ‘a’, ‘b’, ‘c’, ‘d’, ‘e’, ‘f’, )   最大行宽   每行最大行宽不超过 79 个字符   一般续行可使用反斜杠   括号内续行不需要使用反斜杠   EXAMPLE: # 无括号续行, 利用反斜杠 with open(‘/path/to/some/file/you/want/to/read’) as file_1, \ open(‘/path/to/some/file/being/written’, ‘w’) as file_2: file_2.write(file_1.read())   # 括号内续行, 尽量在运算符后再续行 class Rectangle(Blob):   def __init__(self, width, height, color=‘black’, emphasis=None, highlight=0): if (width == 0 and height == 0 and color == ‘red’ and emphasis == ‘strong’ or highlight 100): raise ValueError(“sorry, you lose”) if width == 0 and height == 0 and (color == ‘red’ or emphasis is None): raise ValueError(“I don’t think so -- values are %s, %s” % (width, height))   空行   两行空行用于分割顶层函数和类的定义   单个空行用于分割类定义中的方法   EXAMPLE: # 类的方法定义用单个空行分割,两行空行分割顶层函数和类的定义。 class A(object): def method1(): pass   def method2(): pass   def method3(): pass   模块导入   导入的每个模块应该单独成行   导入顺序如下: (各模块类型导入之间要有空行分割,各组里面的模块的顺序按模块首字母自上而下升序排列)   标准库 相关的第三方库 本地库   EXAMPLE: # 按模块首字母排序导入, 依此递推 import active import adidas import create   错误示例: # 一行导入多模块 import sys, os, knife   # 不按首字母导入 import create import active import beyond   字符串   单引号和双引号作用是一样的,但必须保证成对存在,不能夹杂使用. (建议句子使用双引号, 单词使用单引号, 但不强制.)   EXAMPLE: # 单引号和双引号效果一样 name = ‘JmilkFan’ name = “Hey Guys!”   表达式和

文档评论(0)

1亿VIP精品文档

相关文档