代码之家  ›  专栏  ›  技术社区  ›  Ram Rachum

python docstrings中的字符串操作

  •  8
  • Ram Rachum  · 技术社区  · 16 年前

    我一直在尝试做以下工作:

    #[...]
        def __history_dependent_simulate(self, node, iterations=1,
                                         *args, **kwargs):
            """
            For history-dependent simulations only:
            """ + self.simulate.__doc___
    

    我试图在这里完成的是,为这个私有方法提供与方法文档相同的文档 simulate 除了简短的介绍。这将允许我避免复制粘贴,保留一个较短的文件,而不必每次更新两个函数的文档。

    但它不起作用。有人知道原因吗?有没有解决方案?

    2 回复  |  直到 16 年前
        1
  •  9
  •   Anthony Towns    16 年前

    更好的解决方案可能是使用装饰器,例如:

    def add_docs_for(other_func):  
        def dec(func):  
            func.__doc__ = other_func.__doc__ + "\n\n" + func.__doc__
            return func
        return dec
    
    def foo():
        """documentation for foo"""
        pass
    
    @add_docs_for(foo)
    def bar():
        """additional notes for bar"""
        pass
    
    help(bar) # --> "documentation for foo // additional notes for bar"
    

    这样就可以对docstring进行任意操作。

        2
  •  1
  •   unwind    16 年前

    我想 this section 非常清楚:

    什么是docstring?

    docstring是一个字符串文本, 作为中的第一条语句发生 模块、函数、类或方法 定义。这样的docstring 这个 doc 它的特殊属性 对象。

    所以,它不是一个计算为字符串的表达式,而是 字符串文字 .