前言
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
https://www.cnblogs.com/poloyy/p/15153886.html
Callable
https://www.cnblogs.com/poloyy/p/15154008.html
TypeVar 泛型
源码解析使用方式
任意类型
# 可以是任意类型
T = TypeVar('T')
def test(name: T) -> T:
print(name)
return name
test(11)
test("aa")
# 输出结果
11
aa
指定类型
# 可以是 int,也可以是 str 类型
AA = TypeVar('AA', int, str)
num1: AA = 1
num2: AA = "123"
print(num1, num2)
num3: AA = []
# 输出结果
1 123
自定义泛型类
暂时没搞懂这个有什么用,先不管了
# 自定义泛型
from typing import Generic
T = TypeVar('T')
class UserInfo(Generic[T]): # 继承Generic[T],UserInfo[T]也就是有效类型
def __init__(self, v: T):
self.v = v
def get(self):
return self.v
l = UserInfo("小菠萝")
print(l.get())
# 输出结果
小菠萝
本文介绍了Python的typing模块,包括基本类型提示、类型别名、NewType、Callable以及TypeVar泛型的使用方法。通过示例展示了如何为函数参数和返回值添加类型约束,以及如何创建自定义泛型类。内容涵盖了从简单的类型约束到复杂的数据结构定义,有助于提升代码的可读性和静态检查效率。

2086

被折叠的 条评论
为什么被折叠?



