Python函数的函数标注
概述
函数标注的含义就是对自定义函数的参数,返回值类型明确指示出数据类型。
给函数的参数标注数据类型的方式是:在形参名后跟一个冒号":",在冒号后指明形参的类型
给函数的返回值标注返回的数据类型的方式是:在函数的参数列表和函数的冒号之间,先指定一个箭头“–>并在箭头后指定函数返回的数据类型“”
函数的参数,返回值的标注类型可以通过函数的__annotations__查看
如下面的代码中的函数,参数arg0的参数类型是一个列表,arg1,arg2都是字符串str,返回值也是字符串str。
def foo(arg0:list, arg1:str, arg2:str='hello,world') -> str:
print('Annotations:', foo.__annotations__)
print('arg0 = ', arg0, 'arg1 = ', arg1, 'arg2 = ', arg2)
print('*' * 50)
return arg1 + ' and ' + arg2
print(foo([1,2,3], 'test'))
输出:
E:\Python3\Exercise\venv\Scripts\python.exe E:/Python3/Exercise/venv/02.py
Annotations: {
'arg0': <class 'list'>, 'arg1': <class 'str'>, 'arg2': <class 'str'>, 'return': <class 'str'>}
arg0 = [1, 2, 3] arg1 = test arg2 = hello,world
**************************************************
test and hello,world
Process finished with exit code 0