我在其他人的Python代码中看到他们在函数的docstring之前粘贴了一些检查;像这样的东西:
def func(args):
if x_version != 1.7:
return
"""docstring is here"""
# function body code
# ...
在 或必须在docstring之前放置一些代码以解决任何问题时,是否有任何情况?是否有任何特殊情况需要引入这种风格,或者它总是只是一种不好的风格,因此必须修复到这样的东西?
def func(args):
"""docstring is here"""
if x_version != 1.7:
return
# function body code
# ...
答案 0 :(得分:7)
如果它是函数体中的第一个语句,Python只会选择一个docstring。在它之前放置代码意味着完全忽略字符串:
>>> def func(args):
... if x_version != 1.7:
... return
... """docstring is here"""
...
>>> func.__doc__ is None
True
如果您希望docstring实际上有效,那么永远不会这样做。
来自Python reference documentation:
字符串文字显示为函数体中的第一个语句,将转换为函数的
__doc__
属性,因此转换为函数的文档字符串。
大胆强调我的。