pos*_*sop 5 docstring python-3.x
我正在尝试制作一个将接受替换字段的文档字符串,如下所示
def run_tests(args):
"""run tests on methods in {0}
usage: {0} --tests
""".format(__file__)
pass
Run Code Online (Sandbox Code Playgroud)
但是当我help(run_tests)在解释器中运行时,我没有得到文档字符串。如果我删除 {} 和 .format() 文档字符串将按预期返回。
我想看到类似的输出:
Help on function run_tests in module myfile:
run_tests(args)
runs tests on methods in myfile.py
usage: myfile.py --tests
Run Code Online (Sandbox Code Playgroud)
python3 有没有办法做到这一点?
您必须__doc__在函数声明后编辑函数属性
def run_tests(args):
pass
run_tests.__doc__ = """\
run tests on methods in {0}
usage: {0} --tests
""".format(__file__)
Run Code Online (Sandbox Code Playgroud)
或者为 docring 制作一个装饰器
def doc(arg):
"""Docstring decorator.
arg: Docstring text or object.
"""
import inspect
def decorator(func):
if type(arg) is str:
func.__doc__ = arg
elif inspect.isclass(arg):
func.__doc__ = arg.__doc__
else:
func.__doc__ = None
return func
return decorator
@doc(
f"""run tests on methods in {__file__}
usage: {__file__} --tests
"""
)
def run_tests(args):
pass
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4095 次 |
| 最近记录: |