欢迎您访问 最编程 本站为您分享编程语言代码,编程技术文章!
您现在的位置是: 首页

Python的typing模块:理解与应用TypeVar泛型

最编程 2024-02-17 16:32:12
...

前言


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


源码解析使用方式

image.png


任意类型

# 可以是任意类型
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


image.png

自定义泛型类

暂时没搞懂这个有什么用,先不管了

# 自定义泛型
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())


# 输出结果
小菠萝


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