为什么我不能将格式函数与docstrings一起使用?

Jim*_*y C 3 python docstring

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

def apply_weighting(self, weighting):
    """
    Available functions: {}
    """.format(weightings)
Run Code Online (Sandbox Code Playgroud)

我想要的是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>
Run Code Online (Sandbox Code Playgroud)

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

Mar*_*ers 6

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

您可以在事后更新文档字符串:

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

apply_weighting.__doc__ = apply_weighting.__doc__.format(weightings)
Run Code Online (Sandbox Code Playgroud)