如何为所有类方法添加常量字符串到__doc__?

 百变睛灵_345 发布于 2023-02-13 10:20

我的代码看起来像这样:

constString = """
Default docstring info:
    1
    2
    3"""

class A():

    def A1():
        """
        First unique docstring.
        """
        pass

    def A2():
        """
        Second unique docstring.
        """
        pass
B = A()
print(B.A1.__doc__)

如果我运行此代码,我会重新输出:

First unique docstring.

Second unique docstring.

但是我想通过为类A中的所有方法添加constString来替换方法的docstring.输出必须如下所示:

First unique docstring.
Default docstring info:
1
2
3

Second unique docstring.
Default docstring info:
1
2
3

我怎么能这样做?

1 个回答
  • 函数文档字符串是可写的; 只分配给function.__doc__; 这是一个装饰器,它将一个字符串添加到类的所有方法的docstring中:

    import inspect
    
    def add_documentation(doc):
        if not doc.startswith('\n'):
            doc = '\n' + doc
    
        def decorator(cls):
            for func in filter(inspect.isfunction, vars(cls).values()):
                func.__doc__ += doc
            return cls
    
        return decorator
    

    像这样使用:

    @add_documentation(constString)
    class A:
        def A1(self):
            """
            First unique docstring.
            """
            pass
    
        def A2(self):
            """
            Second unique docstring.
            """
            pass
    

    装饰器在Python 2和3中都有效,只会影响直接在类上定义的方法,而不会影响任何基类.

    2023-02-13 10:21 回答
撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有