代码之家  ›  专栏  ›  技术社区  ›  Jimmy C

为什么我不能对docstring使用format函数?

  •  5
  • Jimmy C  · 技术社区  · 10 年前

    我有一个这样开始的函数:

    def apply_weighting(self, weighting):
        """
        Available functions: {}
        """.format(weightings)
    

    我希望docstring打印可用权重函数的字典。但在检查函数时,它指出没有可用的docstring:

    In [69]: d.apply_weighting?
    Type:       instancemethod
    String Form:<bound method DissectSpace.apply_weighting of <dissect.DissectSpace instance at 0x106b74dd0>>
    File:       [...]/dissect.py
    Definition: d.apply_weighting(self, weighting)
    Docstring:  <no docstring>
    

    怎么会?无法格式化文档字符串吗?

    1 回复  |  直到 10 年前
        1
  •  10
  •   Martijn Pieters    10 年前

    Python解释器查找字符串文本 只有 。添加 .format() 函数定义语法不支持方法调用。解析文档字符串的是编译器,而不是解释器,以及任何变量,如 weightings 当时不可用;此时不执行代码。

    您始终可以在以下事实之后更新文档字符串:

    def apply_weighting(self, weighting):
        """
        Available functions: {}
        """
    
    apply_weighting.__doc__ = apply_weighting.__doc__.format(weightings)