参考文档:https://www.python.org/dev/peps/pep-0484/
函数的形参中可以加:定义形参的类型,好处是python可以根据定义的类型自动引用方法,实际上不会对类型做检查,但是如果形参类型在函数内部不同可能会导致函数运行错误。
->则表示函数返回的类型是什么类型,实际上也是不做检查的
def function1(a:int,b:int)->str:
return a+b
print(function1(1,2))
print(function1("hello ","world"))
print(function1("a",2))
运行结果如下:
C:\Users\18566\AppData\Local\Programs\Python\Python38\python.exe C:/Users/18566/Desktop/APPAutoTest/learn_fenjie/list_tuple_dict_jie.py
Traceback (most recent call last):
3
File "C:/Users/18566/Desktop/APPAutoTest/learn_fenjie/list_tuple_dict_jie.py", line 20, in <module>
hello world
print(function1("a",2))
File "C:/Users/18566/Desktop/APPAutoTest/learn_fenjie/list_tuple_dict_jie.py", line 17, in function1
return a+b
TypeError: can only concatenate str (not "int") to str
Process finished with exit code 1
可以看到虽然定义了形参的类型都是int,实际上str也没有问题,即不会检查
返回定义的是str,查看当返回是int也不会报错
如果不按照输入的建议类型写,函数内部的命令可能会运行出错,如例子中进行了int类型和str类型的拼接。
主要作用是封装后,别人调用的时候可以比较明确的知道输入和输出类型。