本编码规范是对知道创宇研发技能表中提供的PythonCodingRule.pdf文档进行凝练和总结出来的结果,感谢知道创宇的Geek精神与分享精神
此规范较为严格,严格规定了编码格式和命名规则,仅适于本人,对新手可能有跟多的参考意义
尊重原创,本文及演示代码转载需注明
- 当应用这个规则将导致代码可读性下降,即使对于某人来说他已经习惯于按照这条规则来阅读代码了
- 为了和周围的代码保持一致而打破规则(也许是历史原因)
行最大长度 : 79字符
推荐长度 : 72字符
分割方式 : "" , "()" , "{}"
两行空行分割顶层函数和类的定义
一行空行分割方法或函数
额外空行分割相关函数群
类定义与第一个方法定义需要一行空行
先import标准模块,再from ... import第三方模块(绝对路径) ,最后from ... import自建模块
每组导入空一行,一行导入一个包[模块,类等]
紧贴各类括号
紧贴逗号,分号,冒号前
紧贴函数调用参数列表前开放式括号
紧贴再索引或切片括号
二元操作符或运算符或逻辑等两边各留一个空格
默认参数或关键参数"="不留空格
模块名 : 不含下划线 ; 小写 ; 剪短
类名,异常名 : 首字母大写单词串
方法,函数 : 第一个字母小写的首字母大写单词串
属性,实例,变量 : 小写字母串
私有 : 双下划线开头
非公有 : 单下划线开头
使用"is"或"is not"进行对"None"的单值比较
使用字符串方法代替字符串模块
使用startswith()和endswith()检查前后缀而不是使用切片
使用isinstance()判断对象是否是字符串而不是使用type()
判断空序列或字典不要使用len()
书写字符串文字不要依赖有意义的后置空格
不要用"=="比较布尔值
#!/usr/bin/Python# -*- coding: utf-8 -*-'''Pyhton Coding Rule 这是Python编码规范的示例代码,它将向你展示Python编程中一些代码的标准格式帮助提升代码的可读性以及编程效率'''__version__ = "vision: 1.0"import sysimport urllibfrom os import pathfrom types import StringTypesfrom inexistence import *class BaseRules(): '''class BaseRules() 这是一个用于演示的类 ''' def __init__(self, input_=''): self.input = input_ self.__spacerule = 4 self.__maxWords = 79 self.__spliteways = ['//', '()', '{}'] def getSpaceRule(self): PRint self.__spacerule def getMaxWords(self): print self.__maxwords def getSpliteWays(self): for spliteway in self.__spliteways: print splitewayclass PythonRules(BaseRules): '''class PythonRules ''' def __init__(self, input_, output): BaseRules.__init__(input_) self.output = output if isinstance(self.output, StringTypes): if self.output: if self.output.startswith(' '): print 'Do not start with space !' if self.output.endswith(' '): print 'Do not end with space !' else: self.output = ['What', 'the', 'fuck', 'you', 'input', '?'] # 这里其实不太美观~/(≧▽≦)/~啦 for word in self.output: print word,if __name__ == '__main__': baserule = BaseRules() pythonrule = PythonRules('bibibabibo', 'I am erliang')
新闻热点
疑难解答