1. 程式人生 > 實用技巧 >python函式註釋,引數後面加冒號:,函式後面的箭頭→是什麼?

python函式註釋,引數後面加冒號:,函式後面的箭頭→是什麼?

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
"""