一、介绍

Python是一门弱类型的语言,很多时候我们可能不清楚函数参数类型或者返回值类型,很有可能导致一些类型没有指定方法,在写完代码一段时间后回过头看代码,很可能忘记了自己写的函数需要传什么参数,返回什么类型的结果,就不得不去阅读代码的具体内容,降低了阅读的速度,typing模块可以很好的解决这个问题

typing模块的作用:

自python3.5开始,PEP484为python引入了类型注解(type hints)

  • 类型检查,防止运行时出现参数和返回值类型不符合。
  • 作为开发文档附加说明,方便使用者调用时传入和返回参数类型。
  • 该模块加入后并不会影响程序的运行,不会报正式的错误,只有提醒pycharm目前支持typing检查,参数类型错误会黄色提示

二、常用类型

  • int,long,float: 整型,长整形,浮点型;

  • bool,str: 布尔型,字符串类型;

  • List, Tuple, Dict, Set:列表,元组,字典, 集合;

  • Iterable,Iterator:可迭代类型,迭代器类型;

  • Generator:生成器类型;

三、常用代码

from typing import List, Union

def func(a: int, string: str) -> List[int or str]:
list1 = []
list1.append(a)
list1.append(string)
return list1 # 使用or关键字表示多种类型,也可以用Union
def get_next_id(id:int) -> Union[int, None]:
if not isinstance(id ,int):
return
if id>1:
return id
return None print(func(88,""))
print(get_next_id(999)) #pycharm会在传入的参数上黄色提示
print(func(88,[""]))
print(get_next_id(''))

最新文章

  1. ios - NSTimer中target的self是强引用问题
  2. php原型模式的研究
  3. Extjs ComboBox 动态选中第一项
  4. mysql 索引- 笔记
  5. Gallery 图片画廊
  6. web.config connectionStrings 数据库连接字符串的解释
  7. Lexia3 Citroen/Peugeot Diagnostic tool install instruction
  8. .NET下的加密解密大全(1): 哈希加密
  9. Apache HTTP Server mod_session_dbd模块mod_session_dbd.c 安全漏洞
  10. Android Studio rename module Can't rename root module
  11. 权限开发 spring security 3.0.7 序列1 数据库脚本
  12. Link方式导入java项目
  13. 基于Redis的在线用户列表解决方案
  14. javap -s 查看java方法签名
  15. springboot~openfeign从此和httpClient说再见
  16. CSS3_3D 变换
  17. LibreOffice字体问题解决;从window复制到Ubuntu
  18. vue全局API
  19. 在Linux上安装Elasticsearch5.x
  20. [leetcode] 18. Length of Last Word

热门文章

  1. vue keep-alive缓存问题
  2. linux 7 添加永久路由方法
  3. thymeleaf种处理select,radio和文字回显的问题
  4. Bootstrap4入门
  5. mysql 存储过程 随笔
  6. php Excel导出id
  7. js函数中的apply()、call()、bind()方法
  8. ps-奇幻金鱼彩妆
  9. adb shell top 使用
  10. Python匹马行天下之python之父