如何在 Python 中獲取文件字串?


文件字串是字串文字的文件字串,它出現在類、模組、函式或方法定義中,並作為第一條語句編寫。

有兩種型別的文件字串

  • 單行文件字串
  • 多行文件字串

這些主要用於資料科學 /機器 學習 程式設計。

單行文件字串

這種型別的文件字串適合一行。您可以使用單引號(' ...  ')或三引號('''....''')編寫它們。 


示例 1

在以下程式中,我們在函式中聲明瞭一個文件字串,並列印其內容。

def square(x):
'''Returns argument x is squared.'''
return x**x

print (square.__doc__)
help(square)

輸出

Returns argument x is squared.
Help on function square in module __main__:

square(x)
Returns argument x is squared.


多行文件字串

多行文件字串類似於 單行文件字串,唯一的區別在於,在多行文件字串的第一行之後,我們在關閉它之前留一個空行,後面是描述性文字。

示例 2


def function(arg1):
"""Explanation of the function

Parameters:
arg1 (int): Description of arg1

Returns:
int:Returning value


"""

return arg1

print(function.__doc__)

輸出

 您可以觀察到句子“函式說明” 透過一個空行與註釋中的其他內容分隔開。

Explanation of the function

Parameters:
arg1 (int): Description of arg1

Returns:
int:Returning value

 

更新於: 30-Jul-2019

295 次瀏覽

啟動您的 事業

完成課程以獲得認證

開始使用
廣告
© . All rights reserved.