如何在 Python 3 中编写注释

介绍

评论是计算机程序中存在的行,这些行被编译者和解释者忽略,在程序中使用评论可以使代码更易于人读,因为它提供了关于程序的每个部分正在做什么的一些信息或解释。

取决于你的程序的目的,评论可以作为笔记或提醒自己,或者它们可以写成其他程序员能够理解你的代码正在做什么的意图。

一般来说,在写或更新程序时写评论是很好的想法,因为很容易在以后忘记你的思维过程,后来写的评论在长期上可能不那么有用。

前提条件

如果您没有设置编程环境,您可以参考本地编程环境的安装和安装指南(https://www.digitalocean.com/community/tutorial_series/how-to-install-and-set-up-a-local-programming-environment-for-python-3)或适用于您的操作系统(Ubuntu, CentOS, Debian 等)的编程环境(https://www.digitalocean.com/community/tutorial_collections/how-to-install-python-3-and-set-up-a-programming-environment)。

如何合成

Python 中的评论以一个哈希标记(#)和白空间字符开始,并继续到行的尽头。

<$>[info] 信息: 要跟进本教程中的示例代码,请在本地系统上运行python3命令,打开Python交互壳。

一般来说,评论将看起来像这样的东西:

1# This is a comment

因为评论不执行,当你运行一个程序时,你不会看到评论的任何迹象,评论是人类阅读的源代码,而不是计算机执行的。

你好,世界!节目中,评论可能看起来像这样:

1[label hello.py]
2# Print “Hello, World!” to console
3print("Hello, World!")

在一个(LINK0)重复一个(LINK1)的(LINK1)中,评论可能是这样的:

1[label sharks.py]
2# Define sharks variable as a list of strings
3sharks = ['hammerhead', 'great white', 'dogfish', 'frilled', 'bullhead', 'requiem']
4
5# For loop that iterates over sharks list and prints each string item
6for shark in sharks:
7   print(shark)

也就是说,一个没有 indent 的 函数定义将有一个没有 indent 的评论,并且每个接下来的 indent 将有与它评论的代码一致的评论。

例如,这里是如何评论从 如何在Python 3中制作一个简单的计算机程序教程again() 函数,随后每个 indent 级别的代码的评论:

 1[label calculator.py]
 2...
 3# Define again() function to ask user if they want to use the calculator again
 4def again():
 5
 6    # Take input from user
 7    calc_again = input('''
 8Do you want to calculate again?
 9Please type Y for YES or N for NO.
10''')
11
12    # If user types Y, run the calculate() function
13    if calc_again == 'Y':
14        calculate()
15
16    # If user types N, say good-bye to the user and end the program
17    elif calc_again == 'N':
18        print('See you later.')
19
20    # If user types another key, run the function again
21    else:
22        again()

评论是为了帮助程序员,无论是原始程序员还是使用或协作项目的其他人. 如果评论不能与代码库一起正确维护和更新,最好不要包含评论,而不是写一个与代码矛盾或会矛盾的评论。

当评论代码时,你应该寻求对代码背后的 why 回答,而不是 whathow

区块链评论

可以用来解释更复杂的代码或代码,您不希望读者熟悉。

在区块评论中,每个行都以哈希标记和一个单个空间开始,如果需要使用多个段落,则应该由包含单个哈希标记的行分开。

下面是一個區塊評論的例子,它定義了下文所定義的「main()」函數中所發生的事:

 1# The main function will parse arguments via the parser variable. These
 2# arguments will be defined by the user on the console. This will pass
 3# the word argument the user wants to parse along with the filename the
 4# user wants to use, and also provide help text if the user does not
 5# correctly pass the arguments.
 6
 7def main():
 8  parser = argparse.ArgumentParser()
 9  parser.add_argument(
10      "word",
11      help="the word to be searched for in the text file."
12  )
13  parser.add_argument(
14      "filename",
15      help="the path to the text file to be searched through"
16  )
17...

区块评论通常用于操作不太容易理解,因此需要彻底解释,您应该尽量避免对代码进行过度评论,并且应该倾向于信任其他程序员来理解Python,除非您为特定受众撰写。

内地评论

内线评论发生在声明的相同行上,然后是代码本身. 与其他评论一样,它们以哈希符号和单个白色空间字符开始。

一般来说,内部评论看起来像这样:

1[code]  # Inline comment about the code

内线评论应该谨慎使用,但可以有效地解释复杂或复杂的代码部分,如果您认为您可能不记得未来写的代码的一行,或者如果您正在与你知道可能不熟悉代码的各个方面的人合作,它们也可能有用。

例如,如果您在 Python 程序中不使用大量的 数学,您或您的合作者可能不知道以下内容会创建一个复杂的数字,因此您可能希望包含有关此事的内线评论:

1z = 2.5 + 3j  # Create a complex number

内线评论也可以用来解释做某事的原因,或者一些额外的信息,例如:

1x = 8  # Initialize x with an arbitrary number

在线发表的评论只应在必要时使用,并且可以为阅读程序的人提供有用的指导。

评论出测试代码

除了使用评论作为文档代码的方式外,哈希标记还可以用来评论您在测试或调试您目前正在创建的程序时不想执行的代码。

使用哈希标记也可以让你在确定如何设置代码时尝试替代方案,例如,你可以选择在Python游戏中使用一个while循环(https://andsky.com/tech/tutorials/how-to-construct-while-loops-in-python-3)或一个for循环,并且可以评论其中一个或另一个,同时测试并确定哪一个可能是最好的:

 1[label guess.py]
 2import random
 3
 4number = random.randint(1, 25)
 5
 6# number_of_guesses = 0
 7
 8for i in range(5):
 9# while number_of_guesses < 5:
10    print('Guess a number between 1 and 25:')
11    guess = input()
12    guess = int(guess)
13
14    # number_of_guesses = number_of_guesses + 1
15
16    if guess < number:
17        print('Your guess is too low')
18
19    if guess > number:
20        print('Your guess is too high')
21
22    if guess == number:
23        break
24
25if guess == number:
26    print('You guessed the number!')
27
28else:
29    print('You did not guess the number. The number was ' + str(number))

用哈希符号评论代码可以让你尝试不同的编程方法,并通过系统地评论和运行程序部分来帮助你找到错误的来源。

结论

使用您的Python程序中的评论有助于使您的程序更易于阅读,包括您的未来的自我,包括相关和有用的适当的评论可以让其他人更好地与您合作编程项目,并使您的代码的价值更清晰。

從這裡,您可能想閱讀Python的Docstrings in PEP 257(https://www.python.org/dev/peps/pep-0257/),以便為您提供更多資源,以正確地紀錄您的Python項目。

Published At
Categories with 技术
Tagged with
comments powered by Disqus