轉自:https://www.jianshu.com/p/d414e90dc953javascript
Python風格規範 本項目包含了部分Google風格規範和PEP8規範,僅用做內部培訓學習css
Python風格規範 本項目包含了部分Google風格規範和PEP8規範,僅用做內部培訓學習html
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 |
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 ).java
一個文檔字符串應該這樣組織:
1. 首先是一行以句號, 問號或驚歎號結尾的概述(或者該文檔字符串單純只有一行). 接着是一個空行.
2. 接着是文檔字符串剩下的部分, 它應該與文檔字符串的第一行的第一個引號對齊.python
"""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") """
行內註釋是與代碼語句同行的註釋
1. 行內註釋和代碼至少要有兩個空格分隔
2. 註釋由#和一個空格開始sql
x = x + 1 # Compensate for border
每一個文件應該包含一個許可樣板. 根據項目使用的許可(例如, Apache 2.0, BSD, LGPL, GPL), 選擇合適的樣板.json
# -*- coding: utf-8 -*- # (C) JiaaoCap, Inc. 2017-2018 # All rights reserved # Licensed under Simplified BSD License (see LICENSE)
一個函數必需要有文檔字符串, 除非它知足如下條件:
1. 外部不可見
2. 很是短小
3. 簡單明瞭api
文檔字符串應該包含函數作什麼, 以及輸入和輸出的詳細描述
文檔字符串應該提供足夠的信息, 當別人編寫代碼調用該函數時, 他不須要看一行代碼, 只要看文檔字符串就能夠了
對於複雜的代碼, 在代碼旁邊加註釋會比使用文檔字符串更有意義.ruby
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)段. 而且應該遵照和函數參數相同的格式.bash
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
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
# 垂直對齊換行的元素 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
def complex(real, imag=0.0): return magic(r=real, i=imag)
YES:
foo = 1000 # comment long_name = 2 # comment that should not be aligned NO: 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(kl@gmail.com): Use a "*" here for string repetition. # TODO(Zeke) Change this to use relations.
# 不推薦: 操做符離操做數太遠 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)
df.列名
,可使用df['列名']
, 建議使用df.loc[:, '列名']
df.ix
|--docs |--requests | |--__init__.py | |--_internal_utils.py | |--utils.py | |--api.py |--tests |--setup.py |--README.rst |--LICENSE
# -*- 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