(转)Python开发规范
轉自:https://www.jianshu.com/p/d414e90dc953
Python風格規范?本項目包含了部分Google風格規范和PEP8規范,僅用作內部培訓學習
Python風格規范 本項目包含了部分Google風格規范和PEP8規范,僅用作內部培訓學習
命名規范
Python之父推薦的規范
| 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 | ? |
應該避免的名稱
1.單字符名稱 2.包/模塊名中使用連字符(-)而不使用下劃線(_) 3.雙下劃線開頭并結尾的名稱(如__init__)命名約定
1.所謂”內部(Internal)”表示僅模塊內可用, 或者, 在類內是保護或私有的. 2.用單下劃線(_)開頭表示模塊變量或函數是protected的(使用import * from時不會包含). 3.用雙下劃線(__)開頭的實例變量或方法表示類內私有. 4.將相關的類和頂級函數放在同一個模塊里. 不像Java, 沒必要限制一個類一個模塊. 5.對類名使用大寫字母開頭的單詞(如CapWords, 即Pascal風格), 但是模塊名應該用小寫加下劃線的方式(如lower_with_under.py).注釋規范
文檔字符串
Python使用文檔字符串作為注釋方式: 文檔字符串是包, 模塊, 類或函數里的第一個語句. 這些字符串可以通過對象的doc成員被自動提取, 并且被pydoc所用. 我們對文檔字符串的慣例是使用三重雙引號”“”( PEP-257 ).
一個文檔字符串應該這樣組織:
1. 首先是一行以句號, 問號或驚嘆號結尾的概述(或者該文檔字符串單純只有一行). 接著是一個空行.
2. 接著是文檔字符串剩下的部分, 它應該與文檔字符串的第一行的第一個引號對齊.
行內注釋(PEP8)
行內注釋是與代碼語句同行的注釋
1. 行內注釋和代碼至少要有兩個空格分隔
2. 注釋由#和一個空格開始
模塊
每個文件應該包含一個許可樣板. 根據項目使用的許可(例如, Apache 2.0, BSD, LGPL, GPL), 選擇合適的樣板.
# -*- coding: utf-8 -*- # (C) JiaaoCap, Inc. 2017-2018 # All rights reserved # Licensed under Simplified BSD License (see LICENSE)函數和方法
一個函數必須要有文檔字符串, 除非它滿足以下條件:
1. 外部不可見
2. 非常短小
3. 簡單明了
文檔字符串應該包含函數做什么, 以及輸入和輸出的詳細描述
文檔字符串應該提供足夠的信息, 當別人編寫代碼調用該函數時, 他不需要看一行代碼, 只要看文檔字符串就可以了
對于復雜的代碼, 在代碼旁邊加注釋會比使用文檔字符串更有意義.
類
類應該在其定義下有一個用于描述該類的文檔字符串. 如果你的類有公共屬性(Attributes), 那么文檔中應該有一個屬性(Attributes)段. 并且應該遵守和函數參數相同的格式.
class HTTPAdapter(BaseAdapter): """The built-in HTTP Adapter for urllib3. Provides a general-case interface for Requests sessions to contact HTTP and HTTPS urls by implementing the Transport Adapter interface. :param pool_connections: The number of urllib3 connection pools to cache. :param max_retries: The maximum number of retries each connection should attempt. Usage:: >>> import requests >>> s = requests.Session() >>> a = requests.adapters.HTTPAdapter(max_retries=3) >>> s.mount('http://', a) """ def __init__(self, pool_connections, max_retries): self.pool_connections = pool_connections self.max_retries = max_retries塊注釋和行注釋
對于復雜的操作, 應該在其操作開始前寫上若干行注釋. 對于不是一目了然的代碼, 應在其行尾添加注釋.
# We use a weighted dictionary search to find out where i is in # the array. We extrapolate position based on the largest num # in the array and the array size and then do binary search to # get the exact number.if i & (i-1) == 0: # true iff i is a power of 2行長度
換行
空格
模塊導入
TODO注釋
二元運算符換行(PEP8)
# 不推薦: 操作符離操作數太遠 income = (gross_wages +taxable_interest +(dividends - qualified_dividends) -ira_deduction -student_loan_interest)# 推薦:運算符和操作數很容易進行匹配 income = (gross_wages+ taxable_interest+ (dividends - qualified_dividends)- ira_deduction- student_loan_interest)其它規范
Pandas使用規范
目錄結構示例
|--docs |--requests | |--__init__.py | |--_internal_utils.py | |--utils.py | |--api.py |--tests |--setup.py |--README.rst |--LICENSEClass結構示例
# -*- coding: utf-8 -*- # (C) JiaaoCap, Inc. 2017-2018 # All rights reserved # Licensed under Simplified BSD License (see LICENSE) """ requests.api This module contains xxx. This module is designed to xxx. """ # stdlib import os import time from base64 import b64encode # 3p try: import psutil exception ImportError: psutil = None import simplejson as json # project from .utils import current_time from ._internal_utils import internal_func class Response(object): """A user-created :class:`Response <Response>` object. Used to xxx a :class: `JsonResponse <JsonResponse>`, which is xxx :param data: response data :param file: response files Usage:: >>> import api >>> rep = api.Response(url="http://www.baidu.com") """ def __init__(self, data, files, json, url) self.data = data @staticmethod def _sort_params(params): """This is a private static method""" return params def to_json(): """The fully method blala bian shen, xxx sent to the server. Usage:: >>> import api >>> rep = api.Response(url="http://www.baidu.com") >>> rep.to_json() """ if self.url == "www": return True return False相關鏈接
- Google開源項目風格指南: https://zh-google-styleguide.readthedocs.io/en/latest/
- PEP 8 -- Style Guide for Python Code: https://www.python.org/dev/peps/pep-0008/
- Python PEP8 編碼規范中文版: https://blog.csdn.net/ratsniper/article/details/78954852
轉載于:https://www.cnblogs.com/daxiong2014/p/10421681.html
總結
以上是生活随笔為你收集整理的(转)Python开发规范的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: PHP实现四种排序-插入排序
- 下一篇: __getattr__在python2.