python是否有与javascript等价的函数注释?

2024-05-16 06:02:48 发布

您现在位置:Python中文网/ 问答频道 /正文

在Javascript中,编码器可以使用@param{string}选项对函数进行如下注释。你知道吗

Python有一个docstring,但是在阅读https://www.python.org/dev/peps/pep-0257/docstring约定时,我看不到与js等价的东西。你知道吗

下面是一个注释JS函数的示例:

/**
 * generate a random matrix
 * @param {number} n the height of the matrix
 * @param {number} m the width of the matrix
 */
function generateRandomMatrix(n, m) {
    mtrx = []
    for (let i = 0; i < n; i++) {
        mtrx.push([])
        for (let j = 0; j < m; j++) {
            mtrx[i].push(Math.round(Math.random()*10))
        }
    }
    return mtrx
}

上面的注释的python等价物是什么(如果存在)? 特别是@param{number}特性。。。。你知道吗


Tags: ofthe函数numberforparamrandommath
3条回答

是的。它们被称为docstring。见https://www.python.org/dev/peps/pep-0257/

def foo(bar: int, baz: int) -> int:
    """
    Add two numbers

    :param bar: explain bar
    :param baz: explain baz
    :return: int
    """
    return bar + baz

关于Python函数参数的注释也应该包含在docstring中,然后您可以使用Sphinx自动生成文档。Sphinx最初是为Python文档本身创建的。你知道吗

默认情况下,Sphinx采用以下docstring格式(请参见here):

:param [ParamName]: [ParamDescription], defaults to [DefaultParamVal]
:type [ParamName]: [ParamType](, optional)
...
:raises [ErrorType]: [ErrorDescription]
...
:return: [ReturnDescription]
:rtype: [ReturnType]

但是您可以使用Napoleon extension for Sphinx来读取可读性更高(因此是Pythonic)Google Style Docstrings

def fetch_bigtable_rows(big_table, keys, other_silly_variable=None):
    """Fetches rows from a Bigtable.

    Retrieves rows pertaining to the given keys from the Table instance
    represented by big_table.  Silly things may happen if
    other_silly_variable is not None.

    Args:
        big_table: An open Bigtable Table instance.
        keys: A sequence of strings representing the key of each table row
            to fetch.
        other_silly_variable: Another optional variable, that has a much
            longer name than the other args, and which does nothing.
    """

在python中,您将在docstring中这样注释。你知道吗

def generate_random_matrix(n, m):
    """generate a random matrix

     Parameters
     -----------------
     n : int
         the height of the matrix
     m : int 
         the width of the matrix

     Returns
     ----------
     An array with shape (n, m)
    """
    pass

有几条指导方针来看看这个anwser。你知道吗

相关问题 更多 >