Python中的函数参数有冒号 声明后有-> 箭头

在python3.7 环境下 函数声明时能在参数后加冒号,如图:python

def f(ham: str, eggs: str = 'eggs') -> str :
     print("Annotations:", f.__annotations__)
     print("Arguments:", ham, eggs)
     return ham + ' and ' + eggs
 
 print(f("test","abc"))

可能有疑问,python不是动态类型语言 ,难不成还能指定参数类型?函数

来看一下打印结果:
在这里插入图片描述
但同时也确实能传其余类型的值 如:f("test",123)学习

那结果如何呢? 以下:
在这里插入图片描述
固然会报错了啊,返回值是一个字符串,int型不能参与字符串拼接,那参数后写一个:str 和 ->str是什么意思呢?code

PS:若有须要Python学习资料的小伙伴能够加点击下方连接自行获取
note.youdao.com/noteshare?id=2dce86d0c2588ae7c0a88bee34324d76blog

在官方文档指明.__annotations__是函数的参数注释和返回值注释:图片

因此打印出Annotations: {'ham': <class 'str'>, 'eggs': <class 'str'>, 'return': <class 'str'>}文档

其实并无指定类型 只是写函数的人提醒用函数的人最好传什么类型的参数,由于最后须要两个参数进行字符串拼接;字符串

固然,也能够直接写字符串提醒:io

def f(ham: "传一个字符串", eggs: str = 'eggs') -> str :
    print("Annotations:", f.__annotations__)
    print("Arguments:", ham, eggs)
    return ham + ' and ' + eggs

print(f("test",123))

而声明函数后那个箭头:"->" 是返回值的注释,-> str 意思便是提醒函数使用者返回值会是一个str型。学习资料

相关文章
相关标签/搜索