日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > python >内容正文

python

(转)Python开发规范

發布時間:2024/9/5 python 33 豆豆
生活随笔 收集整理的這篇文章主要介紹了 (转)Python开发规范 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

轉自:https://www.jianshu.com/p/d414e90dc953

Python風格規范?本項目包含了部分Google風格規范和PEP8規范,僅用作內部培訓學習

Python風格規范 本項目包含了部分Google風格規范和PEP8規范,僅用作內部培訓學習


命名規范

Python之父推薦的規范

TypePublicInternal
Moduleslower_with_under_lower_with_under
Packageslower_with_under?
ClassesCapWords_CapWords
ExceptionsCapWords?
Functionslower_with_under()_lower_with_under()
Global/Class ConstantsCAPS_WITH_UNDER_CAPS_WITH_UNDER
Global/Class Variableslower_with_underlower_with_under
Instance Variableslower_with_under_lower_with_under (protected) or __lower_with_under (private)
Method Nameslower_with_under()_lower_with_under() (protected) or __lower_with_under() (private)
Function/Method Parameterslower_with_under?
Local Variableslower_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. 接著是文檔字符串剩下的部分, 它應該與文檔字符串的第一行的第一個引號對齊.

"""A user-created :class:`Response <Response>` object.Used to xxx a :class: `JsonResponse <JsonResponse>`, which is xxx:param data: response data :param file: response filesUsage::>>> import api>>> rep = api.Response(url="http://www.baidu.com") """

行內注釋(PEP8)

行內注釋是與代碼語句同行的注釋
1. 行內注釋和代碼至少要有兩個空格分隔
2. 注釋由#和一個空格開始

x = x + 1 # Compensate for border

模塊

每個文件應該包含一個許可樣板. 根據項目使用的許可(例如, 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. 簡單明了

文檔字符串應該包含函數做什么, 以及輸入和輸出的詳細描述
文檔字符串應該提供足夠的信息, 當別人編寫代碼調用該函數時, 他不需要看一行代碼, 只要看文檔字符串就可以了
對于復雜的代碼, 在代碼旁邊加注釋會比使用文檔字符串更有意義.

def simple_func(method, timeout) """Constructs and sends a :class:`Request <Request>`. :param method: method for the new :class:`Request` object. :param timeout: (optional) How many seconds to wait for the server to send data before giving up, as a float, or a :ref:`(connect timeout, read timeout) <timeouts>` tuple. :type timeout: float or tuple :return: :class:`Response <Response>` object :rtype: requests.Response Usage:: >>> import requests >>> req = requests.request('GET', 'http://httpbin.org/get') <Response [200]> """

類應該在其定義下有一個用于描述該類的文檔字符串. 如果你的類有公共屬性(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

行長度

  • 每行不超過80個字符
  • 不要使用反斜杠連接行
  • Python會將 圓括號, 中括號和花括號中的行隱式的連接起來 , 你可以利用這個特點. 如果需要, 你可以在表達式外圍增加一對額外的圓括號.
  • NO: query_sql = "SELECT image_id, image_o, image_width, image_height "\"FROM active_image_tbl "\"WHERE auction_id=:auction_id AND status=1 " \"ORDER BY image_id DESC" YES: agent_sql = ("CREATE TABLE IF NOT EXISTS db_agent (" "id INTEGER PRIMARY KEY AUTOINCREMENT, " "device_id VARCHAR(128) DEFAULT '', " "status INTEGER DEFAULT 1, " "updated_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP, " "created_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP)") 在注釋中,如果必要,將長的URL放在一行上。 Yes: # See details at # http://www.example.com/us/developer/documentation/api/content/v2.0/fication.html

    換行

  • 使用4個空格來縮進代碼
  • 對于行連接的情況, 你應該要么垂直對齊換行的元素, 或者使用4空格的懸掛式縮進(這時第一行不應該有參數):
  • # 垂直對齊換行的元素 foo = long_function_name(var_one, var_two,var_three, var_four)# 4空格的懸掛式縮進(這時第一行不應該有參數) foo = long_function_name(var_one, var_two, var_three,var_four)

    空格

  • 括號內不要有空格
  • YES: spam(ham[1], {eggs: 2}, []) # 注意標點兩邊的空格 NO: spam( ham[ 1 ], { eggs: 2 }, [ ] )
  • 不要在逗號,分號,冒號前面加空格,而應該在它們的后面加
  • YES: if x == 4:print x, y x, y = y, x NO: if x == 4 :print x , y x , y = y , x
  • 二元操作符兩邊都要加上一個空格(=, ==,<, >, !=, in, not ...)
  • 當’=’用于指示關鍵字參數或默認參數值時
  • def complex(real, imag=0.0): return magic(r=real, i=imag)
  • 不要用空格來垂直對齊多行間的標記, 因為這會成為維護的負擔(適用于:, #, =等)
  • YES: foo = 1000 # comment long_name = 2 # comment that should not be alignedNO: foo = 1000 # comment long_name = 2 # comment that should not be aligned

    模塊導入

  • 每個導入應該獨占一行
  • YES: import os import sys from subprocess import Popen, PIPE # PEP8 NO: import sys, os
  • 模塊導入順序
  • 標注庫導入
  • 第三方庫導入
  • 應用程序指定導入
  • 每種分組中, 應該根據每個模塊的完整包路徑按字典序排序, 忽略大小寫.
  • import foo from foo import bar from foo.bar import baz from foo.bar import Quux from Foob import ar

    TODO注釋

  • TODO注釋應該在所有開頭處包含”TODO”字符串, 緊跟著是用括號括起來的你的名字, email地址或其它標識符. 然后是一個可選的冒號. 接著必須有一行注釋, 解釋要做什么
  • 如果你的TODO是”將來做某事”的形式, 那么請確保你包含了一個指定的日期(“2009年11月解決”)或者一個特定的事件
  • # TODO(kl@gmail.com): Use a "*" here for string repetition. # TODO(Zeke) Change this to use relations.

    二元運算符換行(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使用規范

  • pandas數據結構命名 df_、se_
  • df取一列,禁止使用df.列名,可以使用df['列名'], 建議使用df.loc[:, '列名']
  • 禁止使用df.ix
  • 目錄結構示例

    |--docs |--requests | |--__init__.py | |--_internal_utils.py | |--utils.py | |--api.py |--tests |--setup.py |--README.rst |--LICENSE

    Class結構示例

    # -*- 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开发规范的全部內容,希望文章能夠幫你解決所遇到的問題。

    如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。