在python中使用字符串作为注释

在python中使用字符串作为注释,python,Python,我目前正在阅读使用字符串作为注释的python代码。例如,这里有一个函数 def xyz(x): """This is a function that does a thing. Pretty cool, right?""" return 0 使用字符串作为注释有什么意义?看起来真的很奇怪。代码可以编译,但非常混乱 """This is a function that does a thing. Pretty cool, right?""" 这就是所谓的。Python

我目前正在阅读使用字符串作为注释的python代码。例如,这里有一个函数

def xyz(x):
    """This is a function that does a thing.
    Pretty cool, right?"""
    return 0
使用字符串作为注释有什么意义?看起来真的很奇怪。代码可以编译,但非常混乱

"""This is a function that does a thing.
Pretty cool, right?"""
这就是所谓的。Python文档字符串(或docstrings)提供了一种方便的方式,将文档与Python模块、函数、类和方法关联起来

示例

可以使用
\uuu doc\uu
属性从解释器和Python程序访问docstring:

print(xyz.__doc__)
它输出:

This is a function that does a thing.
    Pretty cool, right?
Help on function xyz in module __main__:

xyz(x)
    This is a function that does a thing.
    Pretty cool, right?
另一个用法:

from pydoc import help
print(help(xyz))
它输出:

This is a function that does a thing.
    Pretty cool, right?
Help on function xyz in module __main__:

xyz(x)
    This is a function that does a thing.
    Pretty cool, right?

它们被调用,用于记录代码。像
help()
这样的工具和内置程序也会检查docstring,因此它们不仅适用于代码的读者,也适用于代码的用户。

不是字符串注释!它基本上是多行评论!它被称为
docstring
,由python的帮助/文档系统进行解释,请尝试
help(xyz)
。通常你会描述这个函数所使用的参数类型,以及作为一个返回的期望值。对于我来说,这个返回有一个半参数似乎很奇怪-colon@cricket_007我还在习惯语法:)我不知道
help()
是一个函数,谢谢,这很有帮助。