1. 程式人生 > 其它 >python之宣告函式時指定傳入引數的資料型別(函式引數的註釋)

python之宣告函式時指定傳入引數的資料型別(函式引數的註釋)

python之宣告函式時指定傳入引數的資料型別(實際上是函式引數的註釋)

當你寫的函式方法,要被其他人呼叫時, 你想讓對方知道傳入引數的資料型別, 可以這樣定義:

def demo(name: str, age: 'int > 0'=20)->str:  # ->str 表示該函式的返回值是str型別的
    print(name, type(name))
    print(age, type(age))
    return "hello world"  

demo(1, 2)      # 這裡的引數1會顯示黃色, 但是可以執行不會報錯
demo('小小', 2)  #
正常顯示

執行結果:

<class 'int'># 1 
<class 'int'># 2 

<class 'str'># 小小 
<class 'int'># 2 

總結:

以上是註解表示式的應用方法,註解中最常用的就是類(str 或 int )型別和字串(如 'int>0')。

註解不會做任何處理, 只是儲存在函式的__annotations__屬性(1個字典)中 return 返回的值的註解。

對於註解, python不做檢查, 不做強制, 不做驗證, 什麼操作都不做。

換而言之, 註釋對python直譯器沒有任何意義, 只是為了方便使用函式的人。

函式引數註解

print(demo.__annotations__)

解釋:demo函式的引數註解存放在__annotations__字典中。

執行結果:

{'name': <class 'str'>, 'age': 'int > 0', 'return': <class 'str'>}
去期待陌生,去擁抱驚喜。