在python3.7 環境下 函數聲明時能在參數後加冒號,如圖:python
def f(ham: str, eggs: str = 'eggs') -> str : print("Annotations:", f.__annotations__) print("Arguments:", ham, eggs) return ham + ' and ' + eggs print(f("test","abc"))
可能有疑問,python不是動態類型語言 ,難不成還能指定參數類型?函數
來看一下打印結果:
但同時也確實能傳其餘類型的值 如:f("test",123)學習
那結果如何呢? 以下:
固然會報錯了啊,返回值是一個字符串,int型不能參與字符串拼接,那參數後寫一個:str 和 ->str是什麼意思呢?code
PS:若有須要Python學習資料的小夥伴能夠加點擊下方連接自行獲取
note.youdao.com/noteshare?id=2dce86d0c2588ae7c0a88bee34324d76blog
在官方文檔指明.__annotations__是函數的參數註釋和返回值註釋:圖片
因此打印出Annotations: {'ham': <class 'str'>, 'eggs': <class 'str'>, 'return': <class 'str'>}文檔
其實並無指定類型 只是寫函數的人提醒用函數的人最好傳什麼類型的參數,由於最後須要兩個參數進行字符串拼接;字符串
固然,也能夠直接寫字符串提醒:io
def f(ham: "傳一個字符串", eggs: str = 'eggs') -> str : print("Annotations:", f.__annotations__) print("Arguments:", ham, eggs) return ham + ' and ' + eggs print(f("test",123))
而聲明函數後那個箭頭:"->" 是返回值的註釋,-> str 意思便是提醒函數使用者返回值會是一個str型。學習資料