python注释规范

Python 中的函数注释通常使用文档字符串(docstring)来提供对函数的说明。文档字符串是放置在函数、模块或类的顶部的字符串,用于描述其功能、输入参数、返回值以及其他相关信息。以下是一些建议的 Python 函数注释规范:

使用三重引号: 文档字符串通常由三重引号(单引号或双引号)括起来,以允许跨多行。

def example_function(arg1, arg2):
    """
    This is a docstring that provides a brief description of the function.Args:
    arg1 (int): Description of arg1.
    arg2 (str): Description of arg2.

Returns:
    bool: Description of the return value.
"""

描述函数的作用:

在文档字符串的第一行,提供一个简洁而清晰的概述函数的作用。

说明输入参数

在文档字符串中,使用"Args:"部分详细描述每个参数,包括参数的类型和描述。

说明返回值

在文档字符串中,使用"Returns:"部分描述函数的返回值,包括返回值的类型和描述。

提供示例

如果可能的话,为函数提供使用示例,以便用户更容易理解函数的使用方式。

def example_function(arg1, arg2):
    """
    This is a docstring that provides a brief description of the function.Args:
    arg1 (int): Description of arg1.
    arg2 (str): Description of arg2.

Returns:
    bool: Description of the return value.

Example:
    >>> example_function(5, 'hello')
    True
"""

使用类型提示

尽可能使用函数参数和返回值的类型提示。这有助于提高代码的可读性和 IDE 的代码补全功能。

def example_function(arg1: int, arg2: str) ->; bool:
    """
    This is a docstring that provides a brief description of the function.Args:
    arg1 (int): Description of arg1.
    arg2 (str): Description of arg2.

Returns:
    bool: Description of the return value.
"""

良好的函数注释有助于其他人理解和使用你的代码,同时也为自动生成文档提供了便利。

补充:函数类型提示细节

注释参数: :参数类型
注释返回值 -> 参数类型
本质:函数对象有一个__annotations__的属性,所有对函数的注释都以键值对的形式存储在这个属性里面

当对一个参数有多个注释的时候可以使用字典的形式添加注释

注意,注释位于默认值之前,例如:
def sum(a : int = 10,b):

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值
>