Tutorial

如何在Python 3中使用注释

Published on December 2, 2019
中文
如何在Python 3中使用注释

简介

"注释"是存在于电脑代码中的"被编译器和解释器忽略"的那些文本行。在程序中使用注释将使得代码更易读(方便人去理解代码),因为注释能提供有用的信息去解释代码的每一部分是做什么的。

取决于在程序中的不同目的,你的注释可以是给自己的标记和提醒,或者是帮助其它程序员去理解你的代码。

总的来说,当你写程序或修改程序的过程中,当时写下的注释最为有用。而之后补上的注释长远看来将会没那么有用,因为一段时间之后,你会很容易忘记之前的想法。

注释的句法

Python中的注释是用井号(#)与一个空格作为开头,注释内容将延续到这一行的结尾。

总的来说,注释看上去,会类似与如下所示:

# This is a comment

注释的内容将不作为代码执行,因此运行一个程序你将看不到注释产生的效果。注释是在源代码中方便"人去阅读代码",而不是为了"电脑去运行它"。

在一个"Hello, World!"的程序中,注释可能会是这样:

hello.py
# Print "Hello, World!" to console
print("Hello, World!")

在使用for循环迭代一个列表(list)时,注释可以是这样:

sharks.py
# Define sharks variable as a list of strings
sharks = ['hammerhead', 'great white', 'dogfish', 'frilled', 'bullhead', 'requiem']

# For loop that iterates over sharks list and prints each string item
for shark in sharks:
   print(shark)

注释的缩进应当与它所解释的代码内容保持一致。也就是说一个没有缩进的函数定义应当使用没有缩进的注释。每一层级的代码注释应当与那一层级的代码保持一致。

举个例子,这里是一个来自于如何用Python 3创建简易计算器中,名为again()的函数的注释。我们可以看到每一层级的代码注释都与那一层级的代码缩进保持一致。

calculator.py
...
# Define again() function to ask user if they want to use the calculator again
def again():

    # Take input from user
    calc_again = input('''
Do you want to calculate again?
Please type Y for YES or N for NO.
''')

    # If user types Y, run the calculate() function
    if calc_again == 'Y':
        calculate()

    # If user types N, say good-bye to the user and end the program
    elif calc_again == 'N':
        print('See you later.')

    # If user types another key, run the function again
    else:
        again()

注释是为了帮助程序员(无论是写原始代码的程序员,还是在项目组需要协同的程序员)。如果在一个项目中不能保证注释被合理的维护和更新,那么与其写一个"与代码矛盾,使人产生疑惑"的注释,还不如不写。

当注释代码时,你应当去专注于why的解答,而不是what或者是how。除非代码极其令人疑惑且晦涩难懂,一般情况下看到代码应当就能理解代码的做的是什么(what),以及代码是如何实现的(how)。

批量(多行)注释

批量注释可被用于解释"你不期望读者熟悉这部分代码"的情形。这些较长的注释可以用于解释"注释之后内容"的部分或者全部,或者仅仅是同一级的代码。

在批量注释时,每一行都用一个井号加一个空格作为起始。如果你需要用超过一个段落来解释,那么你应当用"仅有一个井号键"的行,来进行段落的分隔。

这里是一个批量注释的例子,定义了在下面这个main()函数中发生着什么:

# The main function will parse arguments via the parser variable.  These
# arguments will be defined by the user on the console.  This will pass
# the word argument the user wants to parse along with the filename the
# user wants to use, and also provide help text if the user does not 
# correctly pass the arguments.

def main():
  parser = argparse.ArgumentParser()
  parser.add_argument(
      "word",
      help="the word to be searched for in the text file."
  )
  parser.add_argument(
      "filename",
      help="the path to the text file to be searched through"
  )
...

批量注释的典型用处,是在"不是很容易理解的操作中",这类操作需要更多更详尽的解释。你应当尽量避免这类"过度注释",反之你应当去相信其它的Python程序员能理解你的代码(除非你是写给特定的观众,比如教学目的)。

行内注释

行内注释是在一个语句行之中,紧跟着代码本身。和其它注释一样,它用井号(#)与一个空格作为开头。

总的来说,行内注释大概像这样:

[code]  # Inline comment about the code

对于行内注释的使用应当保持节制。但它对于"令人疑惑的、不易懂"的代码非常有效。行内注释对以下两种情形同样有效:1.如果你今后可能不记得你写过的某行代码 2.你与其他程序员协作,你觉得他们可能不完全理解这部分代码的所有方面

举个例子,如果在你的Python程序中使用很多的数学运算,你或是你的合作者,可能不知道如何去理解"怎样去创建一个虚数", 你可以使用以下注释:

z = 2.5 + 3j  # Create a complex number

行内注释同样被用在解释"背后的深层原因",或者是提供更多的信息,比如:

x = 8  # Initialize x with an arbitrary number

注释被放在行内,只适用于"你觉得非常有必要",以及"他们可以为阅读程序提供有用引导"的情形。

测试代码时的注释

除了用于记录解释代码,井号注释同样可以用于在"测试和debug代码时,你不想执行某一行"的情形。也就是说,当你加了几行代码之后程序报错,你可以试着注释掉其中的一部分去帮助定位问题的所在。

使用井号注释还可以帮你(在选择代码设置时)尝试不用的选项。比如说,在一个Python游戏中,选择while循环 或是for循环时,你可以在测试一种循环的时候注释掉另一种循环,去决定哪一种更好:

guess.py
import random

number = random.randint(1, 25)

# number_of_guesses = 0

for i in range(5):
# while number_of_guesses < 5:
    print('Guess a number between 1 and 25:')
    guess = input()
    guess = int(guess)

    # number_of_guesses = number_of_guesses + 1

    if guess < number:
        print('Your guess is too low')

    if guess > number:
        print('Your guess is too high')

    if guess == number:
        break

if guess == number:
    print('You guessed the number!')

else:
    print('You did not guess the number. The number was ' + str(number))

用井号注释点一部分代码可以让你 1.尝试不同的选项,2.通过系统的分步"注释部分代码–重新运行"去定位具体的错误位置。

总结

在Python程序中使用注释可以帮你是你的程序更令人易读,包括今后的你自己。在程序中加入合理且相关的代码,可以方便程序员的团队合作,以及可以让你的代码价值得到更好的体现。

从这之后,你可以选择去阅读Python的Docstrings in PEP 257,去为你Python项目中的文档记录编写提供更多的资源。

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Learn more about us


About the authors

Default avatar
Gongxia Chen

translator


Still looking for an answer?

Ask a questionSearch for more help

Was this helpful?
 
Leave a comment


This textbox defaults to using Markdown to format your answer.

You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!

Try DigitalOcean for free

Click below to sign up and get $200 of credit to try our products over 60 days!

Sign up

Join the Tech Talk
Success! Thank you! Please check your email for further details.

Please complete your information!

Get our biweekly newsletter

Sign up for Infrastructure as a Newsletter.

Hollie's Hub for Good

Working on improving health and education, reducing inequality, and spurring economic growth? We'd like to help.

Become a contributor

Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

Welcome to the developer cloud

DigitalOcean makes it simple to launch in the cloud and scale up as you grow — whether you're running one virtual machine or ten thousand.

Learn more
DigitalOcean Cloud Control Panel