【问题标题】:Using strings as comments in python在python中使用字符串作为注释
【发布时间】:2021-11-07 11:44:06
【问题描述】:

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

def xyz(x):
    """This is a function that does a thing.
    Pretty cool, right?"""
    return 0

使用字符串作为 cmets 有什么意义?看起来真的很奇怪。代码可以编译,但是很混乱。

【问题讨论】:

  • 它不是字符串 cmets!它基本上是multi line cmets!
  • 它被称为docstring,它由python的帮助/文档系统解释,试试help(xyz)。通常你会描述这个函数接受的参数类型以及期望的返回值。
  • 返回有一个分号对我来说似乎很奇怪
  • @cricket_007 我还在习惯语法:)

标签: python


【解决方案1】:
"""This is a function that does a thing.
Pretty cool, right?"""

这称为docstring。 Python 文档字符串(或文档字符串)提供了一种将文档与 Python 模块、函数、类和方法相关联的便捷方式。

示例

可以使用__doc__ 属性从解释器和 Python 程序中访问文档字符串:

print(xyz.__doc__)

它输出:

This is a function that does a thing.
    Pretty cool, right?

另一种用法:

from pydoc import help
print(help(xyz))

它输出:

Help on function xyz in module __main__:

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

【讨论】:

    【解决方案2】:

    它们被称为docstrings,用于记录您的代码。像help() 这样的工具和内置函数也会检查文档字符串,因此它们不仅适用于代码的读者,也适用于代码的用户。

    【讨论】:

    • 不知道help()是个函数,谢谢,很有帮助。
    猜你喜欢
    • 2016-06-06
    • 2020-11-15
    • 2011-02-04
    • 1970-01-01
    • 1970-01-01
    • 2013-08-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多