英文:
Reference Python module docstring from within a class
问题
考虑以下代码:
“”“模块文档。“”“
import argparse
class HandleArgs():
“”“类文档”“”
def __call__(self):
“”“方法文档”“”
parser = argparse.ArgumentParser(description=__doc__)
此代码将尝试使用方法的文档字符串,而不是模块的文档字符串。如何从类内的方法中访问模块的文档字符串?
英文:
Consider the following code:
"""Module documentation."""
import argparse
class HandleArgs()
"""Class documentation"""
def __call__()
"""Method documentation"""
parser = argparse.ArgumentParser(description= __doc__)
This code will try to use the docstring for the method, not the module. How do I access the module docstring from within a method within the class?
答案1
得分: 1
你的陈述不正确。你的代码将使用模块文档字符串。如果你想要使用类的文档字符串,那么使用self.__doc__
。
请参见下面的完整示例。
"""模块文档."""
import argparse
class HandleArgs:
"""类文档."""
def __call__(self):
"""方法文档."""
parser = argparse.ArgumentParser(description=__doc__)
print(parser)
ha = HandleArgs()
ha()
输出
ArgumentParser(prog='docs.py', usage=None, description='模块文档.', formatter_class=<class 'argparse.HelpFormatter'>, conflict_handler='error', add_help=True)
而
"""模块文档."""
import argparse
class HandleArgs:
"""类文档."""
def __call__(self):
"""方法文档."""
parser = argparse.ArgumentParser(description=__doc__)
print(parser)
ha = HandleArgs()
ha()
输出:
ArgumentParser(prog='docs.py', usage=None, description='类文档.', formatter_class=<class 'argparse.HelpFormatter'>, conflict_handler='error', add_help=True)
pc@dev:~/projects/stackoverflow$
英文:
Your statement is not correct. Your code will use the module docstring. If you want to use the class docstring, then self.__doc__
See below for completed example.
"""Module documentation."""
import argparse
class HandleArgs:
"""Class documentation"""
def __call__(self):
"""Method documentation"""
parser = argparse.ArgumentParser(description=__doc__)
print(parser)
ha = HandleArgs()
ha()
Output
> ArgumentParser(prog='docs.py', usage=None, description='Module documentation.', formatter_class=<class 'argparse.HelpFormatter'>, conflict_handler='error', add_help=True)
While
"""Module documentation."""
import argparse
class HandleArgs:
"""Class documentation"""
def __call__(self):
"""Method documentation"""
parser = argparse.ArgumentParser(description=__doc__)
print(parser)
ha = HandleArgs()
ha()
Output:
> ArgumentParser(prog='docs.py', usage=None, description='Class documentation', formatter_class=<class 'argparse.HelpFormatter'>, conflict_handler='error', add_help=True)
pc@dev:~/projects/stackoverflow$
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论