从单行注释到文档字符串,从最佳实践到 IDE 快捷键 —— 一文掌握 Python 注释的所有要点
📚 Python 教程系列 | ⏱ 约 6 分钟阅读 | 🛠 Python 3.x
注释是任何程序不可或缺的一部分。每种编程语言都提供了添加注释的方法。Python 的注释系统非常简单易用。在本指南中,我们将学习 Python 中的注释。注释为开发人员提供了有关代码的有用信息。
我们可以为变量、函数和类添加注释。注释用于说明代码片段的预期用途。让我们来看一些 Python 中的注释示例。
name="Pankaj"# employee name
id=100# employee id
data="#123"# this is comment, data contains # and that is not part of the comment.
# This function adds the two numbers
defadd(x,y):
returnx+y
# This class provides utility functions to work with Strings
classStringUtils:
defreverse(s):
return''.join(reversed(s))
有时,注释无法写在一行中。在这种情况下,我们可以创建一个注释块,或者将注释分成多行。要编写多行注释,我们需要在每一行前面加上井号 (#)。
# This class provides utility functions to work with Strings
# 1. reverse(s): returns the reverse of the input string
# 2. print(s): prints the string representation of the input object
classStringUtils:
defreverse(s):
return''.join(reversed(s))
defprint(s):
print(s)
Python 文档字符串(Docstring)用于为函数、类和模块提供文档。它们用三个双引号(“”)括起来。文档字符串必须紧跟在函数或类声明下方定义。
让我们快速看一下 Python 文档字符串的一些示例。
deffoo():
"""The foo() function needs to be implemented.
Currently, this function does nothing."""
pass
classData:
""" This class is used to hold Data objects information."""
我们可以使用属性访问实体的文档字符串__doc__。
print(foo.__doc__)
print(Data.__doc__)
Python 文档字符串的目的是提供文档。有时你会发现它被滥用,用来添加冗长的注释。然而,这不是推荐的做法。如果你想让注释分成多行,只需在每行前面加上井号 (#) 即可。
我们还可以将多行字符串用作多行注释。根据Guido 的这条推文,它们不会生成任何代码。
'''
This function read employees data from the database
emp_id: employee id, should be int
returns employee object.
'''
defread_emp_from_db(emp_id):
i=int(emp_id)
'''code to read emp data
using the employee unique id number'''
pass
然而,这样做可能会导致缩进问题。此外,代码中出现一个没有任何实际用途的字符串也会让人感到困惑。因此,最好还是使用常规的多行注释,并使用井号 (#) 进行注释。
# count variable
count=10
# foo() function
deffoo():
pass
# This function add two numbers
deffoo(x,y):
returnx+y
# Better to have function defined as below. There is no use of comments.
defadd_two_numbers(x,y):
returnx+y
# {Object Type} - {Usage}
# Data Object - stores the Data fetched from the database
data_obj=Data()
# {Function Short Description}
# {Input Arguments and their types}
# {Return object details}
# {Exception Details}
# This function adds all the elements in the sequence or iterable
# numbers: sequence or iterable, all the elements must be numbers
# Returns the sum of all the numbers in the sequence or iterable
# Throws ArithmeticError if any of the element is not a number
defadd_numbers(numbers):
sum_numbers=0
fornuminnumbers:
sum_numbers+=num
returnsum_numbers
如果您使用的是 Python IDE 或 Jupyter Notebook,您可以使用快捷键注释掉一段代码。
本教程中引用了很多主题,您应该阅读以下教程以进一步了解它们。
如果本文对你有帮助,欢迎 点赞 · 在看 · 分享
关注公众号,持续更新 Python 进阶内容 🚀
— Python 基础系列 · 注释篇 —