从类中引用 Python 模块文档字符串

问题描述 投票:0回答:1

考虑以下代码:

"""Module documentation."""
import argparse

class HandleArgs()
    """Class documentation"""
    def __call__()
        """Method documentation"""
        parser = argparse.ArgumentParser(description= __doc__)

此代码将尝试使用方法的文档字符串,而不是模块。如何从类中的方法中访问模块文档字符串?

python docstring
1个回答
0
投票

你的说法不正确。您的代码将使用模块文档字符串。如果你想使用类文档字符串,那么

self.__doc__

请参阅下面的完整示例。

"""Module documentation."""
import argparse

class HandleArgs:
    """Class documentation"""
    def __call__(self):
        """Method documentation"""
        parser = argparse.ArgumentParser(description=__doc__)
        print(parser)

ha = HandleArgs()
ha()

输出

ArgumentParser(prog='docs.py', usage=None, description='Module documentation.', formatter_class=, conflict_handler='error', add_help=True)

同时

"""Module documentation."""
import argparse

class HandleArgs:
    """Class documentation"""
    def __call__(self):
        """Method documentation"""
        parser = argparse.ArgumentParser(description=__doc__)
        print(parser)

ha = HandleArgs()
ha()

输出:

ArgumentParser(prog='docs.py', usage=None, description='Class documentation', formatter_class=, conflict_handler='error', add_help=True) pc@dev:~/projects/stackoverflow$

© www.soinside.com 2019 - 2024. All rights reserved.