PEP註釋規範範例(1分鐘學習)
技術標籤:# python一分鐘學習python註釋範例程式設計註釋說明規範
目錄
1.Class說明規範
Class說明,對於傳入的引數,屬於parameters, Attributes是指的class的屬性,對於傳入的引數一般是為了初始化類的例項的屬性,而atrributes是指的根據傳入的引數,建立的新的屬性,這些屬性沒有在parameters中出現. method表示類中的方法。
class PreparedConstraint(object):
"""Constraint prepared from a user defined constraint.
On creation it will check whether a constraint definition is valid and
the initial point is feasible. If created successfully, it will contain
the attributes listed below.
Parameters
----------
constraint : {NonlinearConstraint, LinearConstraint`, Bounds}
Constraint to check and prepare.
x0 : array_like
Initial vector of independent variables.
sparse_jacobian : bool or None, optional
If bool, then the Jacobian of the constraint will be converted
to the corresponded format if necessary. If None (default), such
conversion is not made.
finite_diff_bounds : 2-tuple, optional
Lower and upper bounds on the independent variables for the finite
difference approximation, if applicable. Defaults to no bounds.
Attributes
----------
fun : {VectorFunction, LinearVectorFunction, IdentityVectorFunction}
Function defining the constraint wrapped by one of the convenience
classes.
bounds : 2-tuple
Contains lower and upper bounds for the constraints --- lb and ub.
These are converted to ndarray and have a size equal to the number of
the constraints.
keep_feasible : ndarray
Array indicating which components must be kept feasible with a size
equal to the number of the constraints.
Methods
-------
solve
Returns J^-1 * v
update
Updates Jacobian to point `x` (where the function has residual `Fx`)
matvec : optional
Returns J * v
rmatvec : optional
Returns A^H * v
Notes
-----
There may be additional attributes not listed above depending of the
specific solver. Since this class is essentially a subclass of dict
with attribute accessors, one can see which attributes are available
using the `keys()` method.
"""
2.函式說明範例
對於編寫的介面函式必須要有說明,對於一些不開放的函式也儘量寫說明(一些工具函式以及不是很重要或簡單的函式可以沒有函式說明)。函式說明主要包括以下幾個部分(有序):函式概述、Parameters、Returns、See also 、Notes、References、Examples。 每個部分都以“----------”開始,在這行符號的下面開始正式說明每個部分,每個部分結束後以回車隔開,然後接著寫下一個部分。See also是指的其他地方與之關聯的模組,可有可無。References表示引用,該部分的實現參考文獻。Examples部分寫出如何呼叫,儘量寫範例展示呼叫以及結果的整個過程。
def __init__(self, spacing, height, SNR, x_min, x_max, y_min, y_max,
collection_direction):
"""Minimization of scalar function of one or more variables.
Parameters
----------
fun : callable
The objective function to be minimized.
``fun(x, *args) -> float``
where ``x`` is an 1-D array with shape (n,) and ``args``
is a tuple of the fixed parameters needed to completely
specify the function.
x0 : ndarray, shape (n,)
Initial guess. Array of real elements of size (n,),
where 'n' is the number of independent variables.
Returns
-------
res : OptimizeResult
The optimization result represented as a ``OptimizeResult`` object.
Important attributes are: ``x`` the solution array, ``success`` a
Boolean flag indicating if the optimizer exited successfully and
``message`` which describes the cause of the termination. See
`OptimizeResult` for a description of other attributes.
See also
--------
minimize_scalar : Interface to minimization algorithms for scalar univariate functions
show_options : Additional options accepted by the solvers
Notes
-----
This section describes the available solvers that can be selected by the
'method' parameter. The default method is *BFGS*.
**Unconstrained minimization**
Method :ref:`Nelder-Mead <optimize.minimize-neldermead>` uses the
Simplex algorithm [1]_, [2]_. This algorithm is robust in many
applications. However, if numerical computation of derivative can be
trusted, other algorithms using the first and/or second derivatives.
**Bound-Constrained minimization**
。。。。
References
----------
.. [1] Nelder, J A, and R Mead. 1965. A Simplex Method for Function
Minimization. The Computer Journal 7: 308-13.
.. [2] Wright M H. 1996. Direct search methods: Once scorned, now
respectable, in Numerical Analysis 1995: Proceedings of the 1995
Dundee Biennial Conference in Numerical Analysis (Eds. D F
Griffiths and G A Watson). Addison Wesley Longman, Harlow, UK.
191-208.
Examples
--------
Let us consider the problem of minimizing the Rosenbrock function. This
function (and its respective derivatives) is implemented in `rosen`
(resp. `rosen_der`, `rosen_hess`) in the `scipy.optimize`.
>>> from scipy.optimize import minimize, rosen, rosen_der
A simple application of the *Nelder-Mead* method is:
>>> x0 = [1.3, 0.7, 0.8, 1.9, 1.2]
>>> res = minimize(rosen, x0, method='Nelder-Mead', tol=1e-6)
>>> res.x
array([ 1., 1., 1., 1., 1.])
"""
3.py檔案說明範例
每個.py檔案注意最開頭要有說明,先簡單介紹下該檔案的作用,然後指出該檔案中開放的函式,然後通過__all__把開放的函式放進去,以便於通過import *這種方式匯入包的時候,可以全部將開放的介面匯入,而避免非開放的介面匯入。對於每個檔案的說明,可以通過匯入該檔案,然後通過__doc__檢視該模組的說明。
"""
Unified interfaces to minimization algorithms.
Functions
---------
- minimize : minimization of a function of several variables.
- minimize_scalar : minimization of a function of one variable.
"""
__all__ = ['minimize', 'minimize_scalar']
4.引用包的註釋範例
對於需要比較多的引用,注意把引用的給進行分類,按照應用模組進行說明下
# unconstrained minimization
from ._trustregion_dogleg import _minimize_dogleg
from ._trustregion_ncg import _minimize_trust_ncg
from ._trustregion_krylov import _minimize_trust_krylov
# constrained minimization
from .lbfgsb import _minimize_lbfgsb
from .tnc import _minimize_tnc
5.package說明規範
package的說明主要註釋在__init__.py檔案的開頭,對於主包,首先寫明包名,以”=====”與下面的內容進行分隔。然後是Provides,指明該包支援的內容。接著是How to use the documentation,指明如何檢視說明文件。Available subpackages指明該包下可利用的子包有哪些。Utilities指明包的一些工具或基礎內容:如配置、測試、版本等資訊。Viewing documentation using Ipython資訊可有可無,對於咱們這個平臺如果包釋出了的話,可以寫明,沒釋出的話就不用寫這部分了。子包的內容和這個類似,給這些包新增說明的時候,一定要把這個包解釋清楚,可以在註釋裡面新增除了上面提到這些模組以外的內容。
"""
NumPy
=====
Provides
1. An array object of arbitrary homogeneous items
2. Fast mathematical operations over arrays
3. Linear Algebra, Fourier Transforms, Random Number Generation
How to use the documentation
----------------------------
Documentation is available in two forms: docstrings provided
with the code, and a loose standing reference guide, available from
`the NumPy homepage <https://www.scipy.org>`_.
Available subpackages
---------------------
doc
Topical documentation on broadcasting, indexing, etc.
lib
Basic functions used by several sub-packages.
Utilities
---------
test
Run numpy unittests
show_config
Show numpy build configuration
__version__
NumPy version string
Viewing documentation using IPython
-----------------------------------
Start IPython with the NumPy profile (``ipython -p numpy``),
其他注意點:
1.說明儘量以一句話概述,換行再加以具體解釋說明,對於重要的註釋,以雙行等號突出說明:
2.對於上面提到的關於註釋的很多部分都是共用的,比如reference、notes可以用在函式說明中,也可以用在class說明規範裡面,注意靈活使用。
3.行註釋:至少使用兩個空格和語句分開,注意不要使用無意義的註釋
參考:https://github.com/scipy/scipy/blob/master/scipy/optimize/optimize.py