首页
学习
活动
专区
圈层
工具
发布
社区首页 >专栏 >Python - typing 模块 —— NewType

Python - typing 模块 —— NewType

作者头像
小菠萝测试笔记
发布2021-08-23 15:06:31
发布2021-08-23 15:06:31
5720
举报

前言

typing 是在 python 3.5 才有的模块

前置学习

Python 类型提示:https://cloud.tencent.com/developer/article/1864619

常用类型提示

https://cloud.tencent.com/developer/article/1866298

类型别名

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

NewType

可以自定义创一个新类型

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

实际栗子

代码语言:javascript
复制
# 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 类型

类型检查

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

代码语言:javascript
复制
# 'output' is of type 'int', not 'UserId'
output = UserId(23413) + UserId(54341)
print(output)
print(type(output))


# 输出结果
77754
<class 'int'>

Callable

https://cloud.tencent.com/developer/article/1866297

TypeVar 泛型

https://cloud.tencent.com/developer/article/1866293

Any Type

https://cloud.tencent.com/developer/article/1866294

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2021-08-18 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 前言
    • 前置学习
  • 常用类型提示
  • 类型别名
  • NewType
    • 实际栗子
    • 类型检查
    • 使用 UserId 类型做算术运算,得到的是 int 类型数据
  • Callable
  • TypeVar 泛型
  • Any Type
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档