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

看到這個函數:參數後有冒號,函數後還有個 ->,難道是c系列裏的指針?

NONONO!

這是 python 的函數註釋 !

def twoSum(nums: list, target: int) -> list:
    print("函數註釋", twoSum.__annotations__)
    print("參數值打印", nums, target)
    print(type(nums), type(target))

twoSum([1], 9)

看下輸出: 

函數註釋 {'nums': <class 'list'>, 'target': <class 'int'>, 'return': <class 'list'>}
參數值打印 [1] 9
<class 'list'> <class 'int'>

 註釋規則:

  • 參數註釋: 參數名後跟一個冒號,再跟一個expression,這個expression可以是任何形式。
  • 返回值的註釋: -> 表達式
  •  這些註釋信息都是函數的元信息,保存在 函數名.__annotations__字典中.
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章