本編碼規范是對知道創宇研發技能表中提供的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')新聞熱點
疑難解答