zoukankan      html  css  js  c++  java
  • Python 3.x 引入了函数注释

    Python 3.x 引入了函数注释,以增强函数的注释功能,下面是一个普通的自定义函数:

    1.  
      def dog(name, age, species):
    2.  
      return (name, age, species)

    添加了注释的自定义函数:

    1.  
      def dog(name:str, age:(1, 99), species:'狗狗的品种') -> tuple:
    2.  
      return (name, age, species)

    如上,可以使用:对参数逐个进行注释,注释内容可以是任何形式,比如参数的类型、作用、取值范围等等,返回值使用->标注,所有的注释都会保存至函数的属性。
    查看这些注释可以通过自定义函数的特殊属性__annotations__获取,结果会议字典的形式返回:

    1.  
      dog.__annotations__
    2.  
       
    3.  
      # {'age': (1, 99), 'name': str, 'return': tuple, 'species': '狗狗的品种'}

    另外,使用函数注释并不影响默认参数的使用:

    1.  
      def dog(name:str ='dobi', age:(1, 99) =3, species:'狗狗的品种' ='Labrador') -> tuple:
    2.  
      return (name, age, species)

    运行结果:

      1.  
        dog()
      2.  
         
      3.  
        # ('dobi', 3, 'Labrador')
  • 相关阅读:
    BZOJ1049 [HAOI2006]数字序列0
    UOJ265 【NOIP2016】愤怒的小鸟
    #include <deque>
    #include <queue>
    #include <vector>
    #include <set>
    #include <map>
    BZOJ1217:[HNOI2003]消防局的设立
    浅谈贪心
    CF1060B:Maximum Sum of Digits
  • 原文地址:https://www.cnblogs.com/cheyunhua/p/11277101.html
Copyright © 2011-2022 走看看