一、基础写法(单行文档字符串)
适用于功能简单、参数和返回值都很明确的函数。
def add(a, b):
"""计算两个数的和"""
return a + b
# 查看函数备注的方法
print(add.__doc__) # 输出:计算两个数的和
help(add) # 更友好的交互式查看,会显示函数签名+备注
二、标准写法(多行文档字符串)
适用于功能复杂、有多个参数/返回值、需要说明异常的函数,主流有两种风格:
1. google风格(最易读,推荐新手使用)
def calculate_area(shape: str, width: float, height: float = none) -> float:
"""
计算常见几何图形的面积。
支持的图形:矩形(rectangle)、三角形(triangle)
args:
shape: 图形类型,可选值为 "rectangle" 或 "triangle"
width: 宽度/底边长(浮点型)
height: 高度(浮点型),矩形可不传(默认等于width,即正方形)
returns:
计算出的面积(浮点型)
raises:
valueerror: 当shape不是指定值,或宽/高为负数时抛出
"""
if width < 0 or (height and height < 0):
raise valueerror("宽/高不能为负数")
if shape == "rectangle":
height = height or width # 未传height时默认正方形
return width * height
elif shape == "triangle":
if not height:
raise valueerror("三角形必须传入height")
return 0.5 * width * height
else:
raise valueerror(f"不支持的图形类型:{shape}")
# 查看备注
help(calculate_area)
2. sphinx风格(常用于生成官方文档)
def calculate_area(shape: str, width: float, height: float = none) -> float:
"""
计算常见几何图形的面积。
:param shape: 图形类型,可选值为 "rectangle" 或 "triangle"
:type shape: str
:param width: 宽度/底边长(浮点型)
:type width: float
:param height: 高度(浮点型),矩形可不传(默认等于width)
:type height: float
:return: 计算出的面积
:rtype: float
:raises valueerror: 当shape非法或宽/高为负时抛出
"""
# 逻辑和上面一致(省略)
pass
三、关键补充
- 文档字符串的位置:必须紧跟函数定义行,且是函数内的第一个语句。
- 类型注解(可选但推荐):像上面的
shape: str、-> float是python 3.5+支持的类型注解,和文档字符串配合,能让函数的参数/返回值类型更清晰。 - 查看备注的常用方式:
函数名.__doc__:直接获取文档字符串文本。help(函数名):格式化输出函数的完整信息(含参数、备注、异常)。- ide支持:pycharm、vs code等会自动读取文档字符串,在调用函数时显示提示。
总结
- python函数备注首选文档字符串(docstring),而非单行注释,
help()和ide能识别它。 - 简单函数用单行docstring,复杂函数推荐google风格的多行docstring(易读、易维护)。
- 配合类型注解(如
param: type),能让函数的参数/返回值含义更清晰。
到此这篇关于python函数注释备注的写法和使用方法的文章就介绍到这了,更多相关python函数注释备注内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论