python 命名規范


參考Google開源項目風格指南: https://zh-google-styleguide.readthedocs.io/en/latest/google-python-styleguide/contents/

轉載一下其中的命名規范:

命名

module_name, package_name, ClassName, method_name, ExceptionName, function_name, GLOBAL_VAR_NAME, instance_var_name, function_parameter_name, local_var_name.

應該避免的名稱

  1. 單字符名稱, 除了計數器和迭代器.
  2. 包/模塊名中的連字符(-)
  3. 雙下划線開頭並結尾的名稱(Python保留, 例如__init__)

命名約定

  1. 所謂”內部(Internal)”表示僅模塊內可用, 或者, 在類內是保護或私有的.
  2. 用單下划線(_)開頭表示模塊變量或函數是protected的(使用import * from時不會包含).
  3. 用雙下划線(__)開頭的實例變量或方法表示類內私有.
  4. 將相關的類和頂級函數放在同一個模塊里. 不像Java, 沒必要限制一個類一個模塊.
  5. 對類名使用大寫字母開頭的單詞(如CapWords, 即Pascal風格), 但是模塊名應該用小寫加下划線的方式(如lower_with_under.py). 盡管已經有很多現存的模塊使用類似於CapWords.py這樣的命名, 但現在已經不鼓勵這樣做, 因為如果模塊名碰巧和類名一致, 這會讓人困擾.

Python之父Guido推薦的規范

Type Public Internal
Modules lower_with_under _lower_with_under
Packages lower_with_under  
Classes CapWords _CapWords
Exceptions CapWords  
Functions lower_with_under() _lower_with_under()
Global/Class Constants CAPS_WITH_UNDER _CAPS_WITH_UNDER
Global/Class Variables lower_with_under _lower_with_under
Instance Variables lower_with_under _lower_with_under (protected) or __lower_with_under (private)
Method Names lower_with_under() _lower_with_under() (protected) or __lower_with_under() (private)
Function/Method Parameters lower_with_under  
Local Variables lower_with_under  

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM