我有几个函数(a、b和c),我希望它们使用相同的docstring。因此,我的计划是保存行,只编写一次docstring,并将其保存到变量DOCSTRING中。然后我把它放在函数声明下。我在PEP 257上没有发现任何能解决我的问题的东西.
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)实际上我想这可能是work...but我错了,我明白了:
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。
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)当然,它产生了我想要的输出:
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复制到每个函数,,而不需要将它复制到每个函数,那么如何才能得到相同的结果呢?
发布于 2017-05-25 06:47:25
您的问题是,尝试在函数体中设置docstring将无法工作,因为除非函数实际被调用,否则这些行永远不会被计算。你需要的是类似(或相当于)的东西:
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 docstringhttps://stackoverflow.com/questions/44173889
复制相似问题