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 类型

 

类型检查

 

使用 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

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM