3小时入门Python——第五课注释
有时您需要解释代码中某些特定部分的用途。幸运的是,Python 给您提供了满足您需求的机会。您可以留下称为注释的特殊注释。它们对初学者特别有用。在整个课程中,我们将经常使用注释来解释我们的示例。
什么是注释?
Python 注释以**井号#**开头。井号和行尾之间的所有内容均视为注释,并且在运行代码时将被 忽略 。
print("This will run.") # This won't run
在上面的示例中,您可以看到 PEP 8 称为内联注释, 因为它与代码写在同一行。
注释也可以引用其后的代码块:
# Outputs three numbers
print("1")
print("2")
print("3")
我们打算将此类注释主要用于学习目的。现在,是时候找出如何正确注释代码了。
格式化注释
尽管写注释很容易,但是让我们讨论如何按照最佳实践来做注释。
首先,在井号后面应有一个空格 ,在内联注释中,代码末尾与井号之间应有两个空格。在代码末尾和井号之间放置两个以上的空格也是可以接受的,但是最常见的是恰好有两个空格。
print("Learning Python is fun!") # This is a proper comment formatting
print("PEP-8 is important!")#This is a very bad example
将您的注释缩进至与其说明相同的等级。例如,以下示例是错误的:
# this comment is at the wrong place
print("This is a statement to print.")
注释不是 python:不应太长。最好将长注释分成几行:您可以通过在每行的开头添加一个井号来做到这一点:
# Imagine that this is an example of a really long comment
# that we need to spread over three lines, so we continue
# to write it even here.
print("The long comment above explains this line of code.")
跨越多行的注释称为多行或块注释。在 Python 中,没有特殊的方式来指示它们。
您可能 """..."""
还会遇到用三引号引起来的多行注释 ,但是,我们建议您为此使用多个哈希标记。因此,您的代码将符合官方的样式指南。三引号用于文档字符串,或简称 docstring。它们也提供信息,但是它们的使用仅限于功能,方法和其他几种情况。