python docstring是什么

Python (221) 2023-04-25 10:15:58

Docstring是一种文档字符串,用于解释构造的作用。我们在函数、类或方法中将它放在首位来描述其作用。我们用三个单引号或双引号来声明docstring。

>>>defsayhi():
"""
用该函数打印Hi
"""
print("Hi")
>>>sayhi()
Hi

要想获取一个函数的docstring,我们使用它的_doc_属性

>>>sayhi.__doc__
‘
ThisfunctionprintsHi
’

相关推荐:《Python基础教程》

docstring,不仅可以编写代码,同时也能写出文档,保持代码和文档的一致。

docstring说白了就是一堆代码中的注释。

Python的docstring可以通过help函数直接输出一份有格式的文档。

编写test.py

defprintMax(x,y):
'''Printsthemaximumoftwonumbers.
Thetwovaluesmustbeintegers.'''
x=int(x)#converttointegers,ifpossible
y=int(y)
ifx>y:
print(x,'ismaximum')
else:
print(y,'ismaximum')
printMax(3,5)
print(printMax.__doc__)

命令行输入 help(test)

importtest
5ismaximum
Printsthemaximumoftwonumbers.
Thetwovaluesmustbeintegers.
help(test)
Helponmoduletest:
NAME
test-CreatedonSatJun219:05:082018
DESCRIPTION
@author:linzhiwei02
FUNCTIONS
printMax(x,y)
Printsthemaximumoftwonumbers.
Thetwovaluesmustbeintegers.
FILE
/Users/linzhiwei02/Desktop/test.py
THE END

发表回复