python風(fēng)格
命名規(guī)范
The following naming styles are commonly distinguished:
b (single lowercase letter)
B (single uppercase letter)
lowercase
lower_case_with_underscores
UPPERCASE
UPPER_CASE_WITH_UNDERSCORES
CapitalizedWords (or CapWords, or CamelCase -- so named because of the bumpy look of its letters [3] ). This is also sometimes known as StudlyCaps.
Note: When using abbreviations in CapWords, capitalize all the letters of the abbreviation. Thus HTTPServerError is better than HttpServerError.
mixedCase (differs from CapitalizedWords by initial lowercase character!)
模塊名:
lowercase / lower_case_with_underscores,小寫字母,單詞之間用_分割. 如ad_stats.py包名:
lowercase,盡量不要使用_,部分系統(tǒng)不支持。就是文件夾名。類名:
CapitalizedWords,單詞首字母大寫。部分異常名和內(nèi)建變量名也采用CapWords。如AdStats,ConfigUtil
4.異常名
異常也是類,同類名。如果是錯誤,用“Error”后綴全局變量名:
lowercase/lower_case_with_underscores,類似函數(shù)的命名規(guī)范, 建議指模塊內(nèi)部使用的全局變量??梢酝ㄟ^from M import *調(diào)用,通過__all__機(jī)制限制調(diào)用。函數(shù)名:
lowercase/lower_case_with_underscores,mixedCase僅在先前代碼中這種風(fēng)格占據(jù)優(yōu)勢的情況下使用,以保持向后兼容。如get_name()函數(shù)和方法參數(shù)
Always useselffor the first argument to instance methods. Always useclsfor the first argument to class methods.方法名和實例變量
lowercase/lower_case_with_underscores,類似函數(shù)的命名規(guī)范??梢圆捎?code>_前綴標(biāo)志內(nèi)部使用。采用命名重整規(guī)則來避免和子類的命名沖突。常量
UPPERCASE/UPPER_CASE_WITH_UNDERSCORES,用于模塊水平。-
繼承的設(shè)計
始終要確定一個類中的方法和實例變量是否要被公開. 通常, 永遠(yuǎn)不要將數(shù)據(jù)變量公開, 除非你實現(xiàn)的本質(zhì)上只是記錄. 人們總是更喜歡給類提供一個函數(shù)的接口作為替換 (Python 2.2 的一些開發(fā)者在這點上做得非常漂亮).同樣, 確定你的屬性是否應(yīng)為私有的. 私有與非公有的區(qū)別在于: 前者永遠(yuǎn)不會被用在一個派生類中, 而后者可能會. 是的, 你應(yīng)該在大腦中就用繼承設(shè)計好了你的類. 私有屬性必須有兩個前導(dǎo)下劃線, 無后置下劃線. 非公有屬性必須有一個前導(dǎo)下劃線, 無后置下劃線.
公共屬性沒有前導(dǎo)和后置下劃線, 除非它們與保留字沖突, 在此情況下, 單個后置下劃線比前置或混亂的拼寫要好, 例如:
class_優(yōu)于klass. 最后一點有些爭議; 如果相比class_你更喜歡klass, 那么這只是一致性問題.注意: 'cls' is the preferred spelling for any variable or argument which is known to be a class, especially the first argument to a class method.
另外,以下特殊形式可以和以上任何情況結(jié)合使用:
弱“內(nèi)部使用”標(biāo)志 / 非公有屬性:
以_開頭,from M import *不會導(dǎo)入以下劃線開頭的對象/方法/實例變量,但是子類可以使用。如_get_price(),_instance_var類私有屬性 / 方法:
以__開頭(2個下劃線),外部調(diào)用采用命名重整規(guī)則即, inside classFooBar,__boobecomes_FooBar__boo。一般情況下僅用于當(dāng)屬性可被子類繼承時,避免與子類的命名沖突。如__private_var,__get_name()魔法對象或?qū)傩裕?br>
__開頭,__結(jié)尾,一般為python的自有變量,不要以這種方式命名. 如__doc__,__class__下劃線
_后綴:
和保留字沖突的時候使用-
__all__機(jī)制__all__=["fun","class"]__all__可用于模塊導(dǎo)入時限制,如:from module import *,此時被導(dǎo)入模塊若定義了__all__屬性,則只有__all__內(nèi)指定的屬性、方法、類可被導(dǎo)入。若沒定義,則模塊內(nèi)的所有非私有方法/屬性/類將被導(dǎo)入。
術(shù)語
類的方法和實例變量統(tǒng)稱為屬性,a class's methods and instance variables (collectively: "attributes")。
python包含packages, modules, classes, functions, attributes等