注释是对代码的解释说明,是对一个语句、程序段、函数等的解释或提示。程序里的注释是很重要的,它们可以增强程序代码的可读性和可维护性,或者在调试程序功能时,用于临时禁用不需要运行的代码。
注释通常分为行注释和块注释。
行注释
python 的单行注释以 # 开头,任何在 # 后的语句都会被 python 忽略。
# A single line comment, anything after the # is ignored by python.
print('Hello Python!') # and the comment after is ignored
# A comment can also be used to "disable" or comment our code
# print('Hello World!')
块注释
块注释也叫多行注释,在 python 中,可以用三个单引号 (''') 或者三个双引号 (""") 来注释多行内容。
'''
This is a block comment
Anything between the start symbol and the end symbol will be ignored
'''
print('Hello Python!')
"""
This is a block comment
Anything between the start symbol and the end symbol will be ignored
print('Hello World!')
"""
常见问题
print("Hello #Python!")
上述代码中,# 后面的部分并不会被忽略掉,因为这里的 # 处于字符串内部,它就只是一个普通的字符,不代表注释的意思。
拓展阅读
关于怎么使用注释是一个备受争论的话题,观点各式各样。
有的观点认为需要多写注释,便于维护,毕竟程序员自己也有可能不认识自己三天前刚写的代码;
有的观点则认为用注释来解释代码是多余的,如果需要注释来额外解释说明,这意味着代码可能太复杂,这时候需要做的是重写或者重命名,而不是添加注释。
我比较赞同后者,好的注释不应重复代码内容,我们需要注释的是为什么某些东西有效,而不是它们是如何工作的,或者在项目紧张时,用来解释一个代码块有什么缺陷,为什么不是最好方案等,这对修正 bug 尤其有效。
不要在代码中插入不必要的注释,每多一行都会损害代码的可读性,而且注释必须与代码一起维护,而通常不会这样,这会导致误导性注释。
关于代码注释的优秀文章:
Coding Without Comments (codinghorror.com)
Common Excuses Used To Comment Code and What To Do About Them (codeodor.com)