首页 > 编程语言 > 详细

Python 3.x 引入了函数注释

时间:2019-07-31 16:36:04      阅读:90      评论:0      收藏:0      [点我收藏+]

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‘)

Python 3.x 引入了函数注释

原文:https://www.cnblogs.com/cheyunhua/p/11277101.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!