python的函數注釋1
函數注釋示例1:
def fun(name: str, age: '是一個大於零的整數值' = 52) -> '返回值為真': """ 這個是函數的幫助說明文檔,help時會顯示 函數聲明中,name:str name 是參數 :冒號后面 str是參數的注釋。 如果參數有默認值,還要給注釋,如下寫。 age:'是一個大於零的整數值'=52 ->'返回值為真' 是函數返回值的注釋。 這些注釋信息都是函數的元信息,保存在f.__annotations__字典中、 需要注意,python對注釋信息和f.__annotations__的一致性,不做檢查 不做檢查,不做強制,不做驗證!什么都不做。 :param name: :param age: :return: """ return True print(fun.__annotations__)
打印結果如下:
{'name': <class 'str'>, 'age': '是一個大於零的整數值', 'return': '返回值為真'}
函數注釋示例2:
def func(ham: 42, eggs: int = 'spam') -> "Nothing to see here": print("函數注釋", func.__annotations__) print("參數值打印", ham, eggs) print(type(ham), type(eggs)) func("www")
打印結果:
函數注釋 {'ham': 42, 'eggs': <class 'int'>, 'return': 'Nothing to see here'} 參數值打印 www spam <class 'str'> <class 'str'>
解釋說明:
注釋的一般規則是參數名后跟一個冒號(:),然后再跟一個expression,這個expression可以是任何形式。 返回值的形式是 -> int,annotation可被保存為函數的attributes。
以上屬於靜態注釋,還有一種方法叫做動態注釋
動態注釋的原理,就是在函數中或者裝飾器中動態的增加 刪除 更改 注釋內容
f.__annotations__ 是一個字典,可以使用字典的所有操作,這樣就可以動態的更改注釋了
python常用注釋2:
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 """