zoukankan      html  css  js  c++  java
  • Python中的函数参数有冒号 声明后有-> 箭头

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

     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是什么意思呢?

    PS:如有需要Python学习资料的小伙伴可以加点击下方链接自行获取
    note.youdao.com/noteshare?id=2dce86d0c2588ae7c0a88bee34324d76

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

    所以打印出Annotations: {'ham': <class 'str'>, 'eggs': <class 'str'>, 'return': <class 'str'>}

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

    当然,也可以直接写字符串提醒:

    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型。

  • 相关阅读:
    234. Palindrome Linked List
    Remove duplicates
    Unsorted, maximum ==> sorted
    Find one unique integer
    TwoSum
    13. Roman to Integer
    38. Count and Say
    543. Diameter of Binary Tree
    LuoguP1131 [ZJOI2007]时态同步 (树形DP,贪心)
    Luogu3177 [HAOI2015]树上染色 (树形DP)
  • 原文地址:https://www.cnblogs.com/python960410445/p/11960460.html
Copyright © 2011-2022 走看看