通过annotation像强类型language那样指定变量类型,包括参数和返回值的类型
因为Python是弱类型语言,这种指定实际上无效的。所以这种写法叫annotation,就是个注释参考的作用。通过annotation可以极大的提升代码可读性
语法为“var_name: type [= value]"
>>> fake_num: int = 3 # 这里的 int 是annotion,本身并不会限制具体值的类型 >>> fake_num 3 >>> fake_num = 'abc' # 我们也可以把其他类型的值赋予它 >>> fake_num 'abc'
在函数里面用的特别多,用来指定函数参数和返回值的类型
# 指定参数类型 >>> 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'