Use a variable to define multiple functions docstring
我有几个函数(
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | DOCSTRING = ''' This is a docstring for functions: a, b, c''' def a(x, y): DOCSTRING # do stuff with x and y def b(x, y): DOCSTRING # do other stuffs with x and y def c(x, y): DOCSTRING # do some more stuffs with x and y help(a), help(b), help(c) |
我真的认为这可能有效……但我错了,我明白了:
1 2 3 4 5 6 7 8 9 10 11 | Help on function a in module __main__: a(x, y) Help on function b in module __main__: b(x, y) Help on function c in module __main__: c(x, y) |
它一点用处也没有。
我做了第二次尝试,将函数的特殊
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | DOCSTRING = ''' This is a docstring for functions: a, b, c''' def a(x, y): a.__doc__ = DOCSTRING # also tried just __doc__ = DOCSTRING, both didn't work # do stuff with x and y def b(x, y): b.__doc__ = DOCSTRING # also tried just __doc__ = DOCSTRING, both didn't work # do other stuffs with x and y def c(x, y): c.__doc__ = DOCSTRING # also tried just __doc__ = DOCSTRING, both didn't work # do some more stuffs with x and y help(a), help(b), help(c) |
这两种方法得到的输出与之前的尝试相同…
目前有效的是良好的"OLE复制和粘贴"方法:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 | def a(x, y): ''' This is a docstring for functions: a, b, c''' # do stuff with x and y def b(x, y): ''' This is a docstring for functions: a, b, c''' # do other stuffs with x and y def c(x, y): ''' This is a docstring for functions: a, b, c''' # do some more stuffs with x and y help(a), help(b), help(c) |
当然,它产生了我想要的输出:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | Help on function a in module __main__: a(x, y) This is a docstring for functions: a, b, c Help on function b in module __main__: b(x, y) This is a docstring for functions: a, b, c Help on function c in module __main__: c(x, y) This is a docstring for functions: a, b, c |
正如你所看到的,但这种方式会迫使我不得不浪费很多行来写同样的东西…
所以现在,我的问题是,如果我将docstring复制到每个函数,而不必将其复制到每个函数,我如何才能得到相同的结果呢?
您的问题是,试图在函数体中设置docstring将不起作用,因为除非实际调用了函数,否则永远不会计算这些行。你需要的是类似(或相当于)的东西:
1 2 3 4 5 | def c(x, y): # code c.__doc__ = DOCSTRING help(c) |
你应该找个装修工。
1 2 3 4 5 6 7 8 9 | def setdoc(func): func.__doc__ = DOCSTRING return func @setdoc def c(x, y): print("hi") help(c) #Output docstring |