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