簡介
通過annotation像強型別language那樣指定變數型別,包括引數和回傳值的型別
因為Python是弱型別語言,這種指定實際上無效的,所以這種寫法叫annotation,就是個注釋參考的作用,通過annotation可以極大的提升代碼可讀性
語法為“var_name: type [= value]"
快速入門
>>> fake_num: int = 3 # 這里的 int 是annotion,本身并不會限制具體值的型別
>>> fake_num
3
>>> fake_num = 'abc' # 我們也可以把其他型別的值賦予它
>>> fake_num
'abc'
Type annotation在函式里面的應用
在函式里面用的特別多,用來指定函式引數和回傳值的型別
# 指定引數型別
>>> def my_func0(a: int, b: int):
... return a+b
...
>>> my_func0(1, 2)
3
>>> my_func0('a', 'b')
'ab'
#指定引數型別和回傳值型別
>>> def my_func1(a: int, b: int) -> int:
... return a+b
#指定引數型別和回傳值型別,并給引數默認值
>>> def my_func(a: int = 0, b: int = 0) -> int:
... return a+b
...
>>> my_func()
0
>>> my_func(1)
1
>>> my_func(1, 1)
2
>>> my_func('a', 'b')
'ab'
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/458456.html
標籤:其他
上一篇:Java基礎知識復習
下一篇:python中的函式
