zoukankan      html  css  js  c++  java
  • python定义函数时,指定要传入参数的数据类型

    python定义函数时,指定要传入参数的数据类型
    原创小小臭臭g 最后发布于2019-02-13 18:14:49 阅读数 9537  收藏
    展开
    当你写的函数方法,要被其他人调用时, 你想让他知道传入参数的数据类型, 可以这样定义
     
     
    def demo(name: str, age: 'int > 0'=20)->str:  # ->str 表示该函数的返回值是str类型的
        print(name, type(name))
        print(age, type(age))
        return "hello world"  
    demo(1, 2)      # 这里的参数1会显示黄色, 但是可以运行不会报错
     
    # 1 <class 'int'>
    # 2 <class 'int'>
     
     
    demo('小小', 2)  # 正常显示
     
    # 小小 <class 'str'>
    # 2 <class 'int'>
     
    """
        以上是注解表达式的应用方法, 注解中最常用的就是  类(str 或 int )类型 和 字符串(如 'int>0')  
        
        注解不会做任何处理, 只是存储在函数的__annotations__属性(1个字典)中   return 返回的值的注解
        
        对于注解, python不做检查, 不做强制, 不做验证, 什么操作都不做.  换而言之, 注释对python解释器没有任何意义, 只是为了方便使用函数的人  
    """
    print(demo.__annotations__)
    {'name': <class 'str'>, 'age': 'int >0 ', 'return': <class 'str'>}
    # 了解python函数更多相关
    ————————————————
    版权声明:本文为CSDN博主「小小臭臭g」的原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接及本声明。
    原文链接:https://blog.csdn.net/qq_42327755/article/details/87196150

  • 相关阅读:
    【leetcode】416. Partition Equal Subset Sum
    【leetcode】893. Groups of Special-Equivalent Strings
    【leetcode】892. Surface Area of 3D Shapes
    【leetcode】883. Projection Area of 3D Shapes
    【leetcode】140. Word Break II
    【leetcode】126. Word Ladder II
    【leetcode】44. Wildcard Matching
    【leetcode】336. Palindrome Pairs
    【leetcode】354. Russian Doll Envelopes
    2017.12.22 英语面试手记
  • 原文地址:https://www.cnblogs.com/grj001/p/12222969.html
Copyright © 2011-2022 走看看