python函數注釋


python函數注釋,參數后面加冒號:,函數后面的箭頭→是什么?

python的函數注釋:

def f(text:str,max_len:'int>0'=80) ->str:
	"""這個是函數的幫助說明文檔,help時會顯示"""
    return True
"""
函數聲明中,text:str
text 是參數 :冒號后面  str是參數的注釋。
如果參數有默認值,還要給注釋,如下寫。
max_len:'int>0'=80

->str 是函數返回值的注釋。

這些注釋信息都是函數的元信息,保存在f.__annotations__字典中、

需要注意,python對注釋信息和f.__annotations__的一致性,不做檢查
不做檢查,不做強制,不做驗證!什么都不做。
"""

  

函數注釋示例:

def f(ham: 42, eggs: int = 'spam') -> "Nothing to see here":
    print("函數注釋", f.__annotations__)
    print("參數值打印", ham, eggs)
    print(type(ham),type(eggs))

f("www")

 

返回信息:

函數注釋 {'ham': 42, 'eggs': <class 'int'>, 'return': 'Nothing to see here'}
參數值打印 www spam
<class 'str'> <class 'str'>

 

解釋說明:

注釋的一般規則是參數名后跟一個冒號(:),然后再跟一個expression,這個expression可以是任何形式。

返回值的形式是 -> int,annotation可被保存為函數的attributes。

 

以上屬於靜態注釋,還有一種方法叫做動態注釋

動態注釋的原理,就是在函數中或者裝飾器中動態的增加 刪除 更改 注釋內容

f.__annotations__ 是一個字典,可以使用字典的所有操作,這樣就可以動態的更改注釋了

 

大多數情況,我使用的是一下方法,進行注釋說明

def foo():
  """ This is function foo"""

  

 


Google風格
"""
This is a groups style docs.

Parameters:
  param1 - this is the first param
  param2 - this is a second param

Returns:
	This is a description of what is returned

Raises:
	KeyError - raises an exception
"""

  

 


Rest風格
"""
This is a reST style.

:param param1: this is a first param
:param param2: this is a second param
:returns: this is a description of what is returned
:raises keyError: raises an exception
"""

  

 
 原文鏈接:https://blog.csdn.net/sunt2018/article/details/83022493
 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM