【问题标题】:Python module docstringPython 模块文档字符串
【发布时间】:2020-04-10 13:20:02
【问题描述】:

如何从我的主文件中打印我的 python 模块文件的文档字符串?假设我有一个名为 Projectile.py 的 python 模块文件,它在其中定义了一个名为 Projectile 的类。然后我有另一个名为 main.py 的 python 文件。在 main 中,我想访问模块级别的文档字符串。我该怎么做?
我知道如何打印类和方法的文档字符串。 例如,要从我的主文件中打印类级别的文档字符串,只需:

print(Projectile.__doc__)

Output:  This is the class docstring:  Simulates the flight of simple projectiles near the earth's surface, ignoring wind resistance. Tracking is done in two dimensions, height (y) and distance (x).

但是如何打印模块级别的文档字符串?谢谢!

     """This is the module docstring"""
        from graphics import *
        from math import *

        class Projectile:
            """This is the class docstring:  Simulates the flight of simple projectiles near the earth's surface, 
               ignoring wind resistance. Tracking is done in two dimensions, height (y) and distance (x)."""

            # Constructor - TO INITIALIZE INSTANCE VARIABLES
            """This is the constructor docstring"""
            def __init__(self, angle, velocity, height):
                self.initialVelocity = velocity
                self.xpos = 0.0

【问题讨论】:

    标签: python module docstring


    【解决方案1】:

    您可以使用__doc__ 字段获取文档字符串:

    import x; print(x.__doc__)
    

    或者使用help函数获取交互式帮助:

    import x; help(x)
    

    【讨论】:

    • 这会打印出我的 Projectile.py 文件中的所有信息,但不会打印文件/模块顶部的文档字符串。在我的示例中,从我的 main.py 文件中,我试图打印出文档字符串“”“这是模块文档字符串”“”。
    • 知道了。我扩展了我的答案。
    • 当我执行 print(Projectile.__doc__) 时,它会打印我的类文档字符串,而不是模块文档字符串。这是因为我将我的模块命名为与我的班级相同吗?
    • 如何导入Projectile类?不要使用from Projectile import Projectile
    • 呃!天哪,就是这样!谢谢!
    猜你喜欢
    • 2023-01-04
    • 2021-11-06
    • 2023-02-24
    • 2021-05-03
    • 1970-01-01
    • 2016-08-09
    • 2022-12-06
    • 2017-09-25
    • 1970-01-01
    相关资源
    最近更新 更多