我有几个函数(public class FirstTest {
@Test()
public void test {
System.out.println("Hello TesNG!");
}
,a
和b
),我希望它们使用相同的文档字符串。因此,我的计划是仅通过编写docstring一次来保存行,并将其保存到变量c
。然后我把它放在函数声明下。我在PEP 257找不到解决我问题的任何内容......
DOCSTRING
我实际上认为它可能有效...但我错了,我得到了这个:
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)
它根本没用。
我做了第二次尝试,将函数的特殊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)
属性更改为我的文档字符串__doc__
:
DOCSTRING
两种方法都获得了与之前尝试相同的输出...
目前最有效的是复制粘贴方法:
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)
当然,它会产生我想要的输出:
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)
正如你所看到的,但这种方式会迫使我不得不浪费多条线来写同样的东西......
现在,我的问题是,如何将文档字符串复制到每个单独的函数,没有必须将其复制到每个函数?
答案 0 :(得分:3)
您的问题是尝试在函数体中设置文档字符串是行不通的,因为除非实际调用该函数,否则永远不会评估这些行。你需要的东西是(或等同于):
def c(x, y):
# code
c.__doc__ = DOCSTRING
help(c)
您想要使用装饰器。
def setdoc(func):
func.__doc__ = DOCSTRING
return func
@setdoc
def c(x, y):
print("hi")
help(c) #Output docstring