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

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>

怎么会?无法格式化docstring吗?

最佳答案

python解释器只查找字符串文本。不支持添加.format()方法调用,函数定义语法不支持。是编译器解析出docstring,而不是解释器,并且像weightings这样的任何变量当时都不可用;此时没有代码执行。
您始终可以在以下情况之后更新docstring:

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

apply_weighting.__doc__ = apply_weighting.__doc__.format(weightings)

10-06 05:23