Python - typing 模块 —— NewType

简介: Python - typing 模块 —— NewType

前言


typing 是在 python 3.5 才有的模块

 

前置学习

Python 类型提示:https://www.cnblogs.com/poloyy/p/15145380.html

 

常用类型提示


https://www.cnblogs.com/poloyy/p/15150315.html

 

类型别名


https://www.cnblogs.com/poloyy/p/15153883.html

 

NewType


可以自定义创一个新类型

  • 主要用于类型检查
  • NewType(name, tp) 返回一个函数,这个函数返回其原本的值
  • 静态类型检查器会将新类型看作是原始类型的一个子类
  • tp 就是原始类型

 

实际栗子

# NewType
from typing import NewType
UserId = NewType('UserId', int)
def name_by_id(user_id: UserId) -> str:
    print(user_id)
UserId('user')  # Fails type check
num = UserId(5)  # type: int
name_by_id(42)  # Fails type check
name_by_id(UserId(42))  # OK
print(type(UserId(5)))
# 输出结果
42
42
<class 'int'>


可以看到 UserId 其实也是 int 类型

 

类型检查

image.png


使用 UserId 类型做算术运算,得到的是 int 类型数据

# 'output' is of type 'int', not 'UserId'
output = UserId(23413) + UserId(54341)
print(output)
print(type(output))
# 输出结果
77754
<class 'int'>


Callable


https://www.cnblogs.com/poloyy/p/15154008.html

 

TypeVar 泛型


https://www.cnblogs.com/poloyy/p/15154196.html

 

Any Type


https://www.cnblogs.com/poloyy/p/15158613.html

 

Union


https://www.cnblogs.com/poloyy/p/15170066.html

 

Optional


https://www.cnblogs.com/poloyy/p/15170297.html

相关文章
|
1天前
|
Go Python
通过 atexit 模块让 Python 实现 Golang 的 defer 功能
通过 atexit 模块让 Python 实现 Golang 的 defer 功能
10 2
|
10天前
|
JSON API 数据格式
30天拿下Python之requests模块
30天拿下Python之requests模块
23 7
|
10天前
|
人工智能 数据可视化 搜索推荐
Python异常模块与包
Python异常模块与包
|
9天前
|
Linux Python Windows
一个Python模块Pendulum的问题
一个Python模块Pendulum的问题
16 0
|
10天前
|
API Python
30天拿下Python之matplotlib模块
30天拿下Python之matplotlib模块
|
10天前
|
SQL 数据处理 数据库
30天拿下Python之pandas模块
30天拿下Python之pandas模块
12 0
|
10天前
|
存储 索引 Python
30天拿下Python之numpy模块
30天拿下Python之numpy模块
13 0
|
10天前
|
开发者 Python
30天拿下Python之logging模块
30天拿下Python之logging模块
|
10天前
|
安全 索引 Python
30天拿下Python之collections模块
30天拿下Python之collections模块
|
10天前
|
SQL 数据库连接 数据库
30天拿下Python之sqlite3模块
30天拿下Python之sqlite3模块