python - 如何在doc字符串中包含变量?

kdu*_*ubs 4 python

我正在使用cmd模块.有一个命令,我想像这样记录:

def do_this(self,arg)
    "this command accepts these values {values}".format(values="legal values")
Run Code Online (Sandbox Code Playgroud)

理由是我只想输入一次合法价值清单.我发现我可以稍后更改文档字符串,但我认为这是一个黑客攻击.有没有办法做到这一点?

Ant*_*ala 6

之后更改文档字符串(通过分配do_this.__doc__)是唯一的方法.

或者,如果你希望它看起来更好,你可以使用装饰器 - 但它仍然分配给do_this.__doc__.

def doc(docstring):
    def document(func):
        func.__doc__ = docstring
        return func

    return document

@doc("this command accepts these values: {values}".format(values=[1, 2, 3])
def do_this(self, arg):
    pass
Run Code Online (Sandbox Code Playgroud)