前言
typing 是在 python 3.5 才有的模块
前置学习
Python 类型提示:https://www.cnblogs.com/poloyy/p/15145380.html
常用类型提示
https://www.geek-share.com/detail/2840288720.html
类型别名
https://www.cnblogs.com/poloyy/p/15153883.html
NewType
https://www.geek-share.com/detail/2840288661.html
Callable
https://www.geek-share.com/detail/2840288660.html
TypeVar 泛型
源码解析使用方式
任意类型
# 可以是任意类型T = TypeVar(\'T\')def test(name: T) -> T:print(name)return nametest(11)test(\"aa\")# 输出结果11aa
指定类型
# 可以是 int,也可以是 str 类型AA = TypeVar(\'AA\', int, str)num1: AA = 1num2: AA = \"123\"print(num1, num2)num3: AA = []# 输出结果1 123
自定义泛型类
暂时没搞懂这个有什么用,先不管了
# 自定义泛型from typing import GenericT = TypeVar(\'T\')class UserInfo(Generic[T]): # 继承Generic[T],UserInfo[T]也就是有效类型def __init__(self, v: T):self.v = vdef get(self):return self.vl = UserInfo(\"小菠萝\")print(l.get())# 输出结果小菠萝
Any Type
https://www.geek-share.com/detail/2840288600.html
Union
https://www.geek-share.com/detail/2840537300.html
Optional
https://www.geek-share.com/detail/2840542100.html