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

Python - typing 模块 —— TypeVar 泛型

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

前言

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

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

Callable

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

TypeVar 泛型

源码解析使用方式

任意类型

代码语言:javascript
复制
# 可以是任意类型
T = TypeVar('T')


def test(name: T) -> T:
    print(name)
    return name


test(11)
test("aa")


# 输出结果
11
aa

指定类型

代码语言:javascript
复制
# 可以是 int,也可以是 str 类型
AA = TypeVar('AA', int, str)

num1: AA = 1
num2: AA = "123"
print(num1, num2)

num3: AA = []


# 输出结果
1 123

自定义泛型类

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

代码语言:javascript
复制
# 自定义泛型
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://cloud.tencent.com/developer/article/1866294

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

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

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

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

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 前言
    • 前置学习
  • 常用类型提示
  • 类型别名
  • NewType
  • Callable
  • TypeVar 泛型
    • 源码解析使用方式
    • 任意类型
    • 指定类型
    • 自定义泛型类
  • Any Type
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档