Skip to content

Python 注释

注释是任何程序不可或缺的一部分。每种编程语言都提供了添加注释的方法。Python 的注释系统非常简单易用。在本指南中,我们将学习 Python 中的注释。注释为开发人员提供了有关代码的有用信息。

如何在Python中编写注释?

  • Python 注释以 # 字符开头,并延伸到行尾。
  • 我们可以从行首开始添加注释,注释可以放在一些空格或代码之后。
  • 如果字符串字面量中存在井号字符,则该井号字符是该字符串的一部分。

Python 注释示例

我们可以为变量、函数和类添加注释。注释用于说明代码片段的预期用途。让我们来看一些 Python 中的注释示例。

1.变量注释

python
name = "Pankaj"  # employee name
id = 100  # employee id
 
data = "#123"  # this is comment, data contains # and that is not part of the comment.

2. 函数注释

python
# This function adds the two numbers
def add(x, y):
    return x+y

Python 注释

3. 类的注释

python
# This class provides utility functions to work with Strings
class StringUtils:
 
    def reverse(s):
        return ''.join(reversed(s))

Python 注释块或多行注释

有时,注释无法写在一行中。在这种情况下,我们可以创建一个注释块,或者将注释分成多行。要编写多行注释,我们需要在每一行前面加上井号 (#)。

python
# 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
class StringUtils:
 
    def reverse(s):
        return ''.join(reversed(s))
     
    def print(s):
        print(s)

Python 多行注释

使用 Python 文档字符串作为多行注释

Python 文档字符串(Docstring)用于为函数、类和模块提供文档。它们用三个双引号(“”)括起来。文档字符串必须紧跟在函数或类声明下方定义。

让我们快速看一下 Python 文档字符串的一些示例。

python
def foo():
    """The foo() function needs to be implemented.
    Currently, this function does nothing."""
    pass
 
class Data:
    """ This class is used to hold Data objects information."""

我们可以使用属性访问实体的文档字符串__doc__。

python
print(foo.__doc__)
print(Data.__doc__)

Python 文档字符串注释

使用文档字符串来指定长的多行注释是否是个好主意?

Python 文档字符串的目的是提供文档。有时你会发现它被滥用,用来添加冗长的注释。然而,这不是推荐的做法。如果你想让注释分成多行,只需在每行前面加上井号 (#) 即可。

Python 多行字符串作为多行注释

我们还可以将多行字符串用作多行注释。根据Guido 的这条推文,它们不会生成任何代码。

python
'''
This function read employees data from the database
emp_id: employee id, should be int
returns employee object.
'''
def read_emp_from_db(emp_id):
    i = int(emp_id)
    '''code to read emp data
    using the employee unique id number'''
    pass

然而,这样做可能会导致缩进问题。此外,代码中出现一个没有任何实际用途的字符串也会让人感到困惑。因此,最好还是使用常规的多行注释,并使用井号 (#) 进行注释。

Python 注释最佳实践

  • 务必提供有意义的注释,以明确实体的用途。
  • 最好将过长的评论分成多行。
  • 请勿在评论中使用不文明语言。
  • 注释要简洁明了。没人想在代码注释里读小说。
  • 避免发表毫无用处、不提供任何有用信息的评论。以下是一些无用评论的示例。
python
# count variable
count = 10
 
# foo() function
def foo():
    pass
  • 有时注释是不必要的。实体本身的名称就足够了。我们来看一个例子。
python
# This function add two numbers
def foo(x, y):
    return x + y
 
# Better to have function defined as below. There is no use of comments.
def add_two_numbers(x, y):
    return x + y
  • 建立一套评论系统总是有益的。当组织内有众多团队成员和多个项目时,建议使用评论策略。例如,您可以这样定义评论策略:
python
# {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
 
def add_numbers(numbers):
    sum_numbers = 0
    for num in numbers:
        sum_numbers += num
    return sum_numbers

Python 注释快捷键:注释掉代码块

如果您使用的是 Python IDE 或 Jupyter Notebook,您可以使用快捷键注释掉一段代码。

  • macOS 注释快捷键– 选择要注释的行,然后按Command+/,它会自动在每行开头添加 # 号,将其转换为注释块。如果是空行,它会在行首添加 # 号,您可以直接输入注释。
  • Windows 和 Linux 注释快捷键– 使用**Ctrl+/**将代码块转换为注释。

总结

  • Python 注释系统很简单,总是以 # 开头。
  • Python 文档字符串用于编写文档,不应将其误用于多行注释。
  • 多行注释请以井号 (#) 开头。
  • 遵循最佳实践向程序添加评论。
  • 在与众多团队成员合作时,制定注释规则始终是一个好主意。

接下来是什么?

本教程中引用了很多主题,您应该阅读以下教程以进一步了解它们。