Python - typing 模块 —— TypeVar 泛型
2024-10-19 12:59:24
前言
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()) # 输出结果
小菠萝
Any Type
https://www.cnblogs.com/poloyy/p/15158613.html
最新文章
- CentOS 6.6 升级GCC G++ (当前最新版本为v6.1.0) (完整)
- ACM/ICPC 之 昂贵的聘礼-最短路解法(POJ1062)
- ios cell左滑删除
- Ubuntu14.04下安装Hadoop2.5.1 (单机模式)
- 优化Hibernate所鼓励的7大措施
- Vue.js相关知识3-路由
- cojs 疯狂的字符串 题解报告
- 前端开发bower包管理器
- Canvas、Paint、的简单使用及辅助类(Path、Shader、简介)
- jsp fmt标签详解
- 重写轮子之 kNN
- sublime 使用快捷键
- 最近工作再弄基于bootstrap的定制sass
- 2019.03.26 bzoj4446: [Scoi2015]小凸玩密室(树形dp)
- 早期自学jQuery-一入门
- Problem B: 平面上的点——Point类 (II)
- SDOI2017 R2泛做
- RxJava【创建】操作符 create just from defer timer interval MD
- Python Web学习笔记之TCP的3次握手与4次挥手过程
- kibana 与 grafana
热门文章
- shell 中()、[]、{}、(())、[[]]等各种括号的使用
- 18 shell 重定向以及文件描述符
- Spring Boot中的那些生命周期和其中的可扩展点(转)
- vue3 script setup 定稿
- python 10篇 操作mysql
- C语言:条件编译
- java集合(4)-Set集合
- Scala学习——简介
- Kettle——简介
- create-react-app 创建的项目执行npm run eject后,运行报错