Python 的 泛型类型提示
等级 5365 次按键
这使用TypeVar创建泛型Stack类。泛型允许与任何类型一起工作的类型安全容器。
Python 代码
# 从typing模块导入TypeVar和Generic# 用于创建泛型类和函数1from typing import TypeVar, Generic2 # T是表示任何类型的类型变量# 在使用时作为实际类型的占位符3T = TypeVar("T")4 # Stack继承Generic[T]成为泛型# T将被替换为实际类型如int5class Stack(Generic[T]): # __init__返回类型为None # 初始化空栈6 def __init__(self) -> None: # _items类型为T的列表 # 存储栈元素7 self._items: list[T] = []8 # push将类型T的项添加到栈 # 返回None9 def push(self, item: T) -> None: # append添加到列表末尾10 self._items.append(item)11 # pop移除并返回类型T的项 # 返回顶部元素12 def pop(self) -> T: # pop从列表末尾移除13 return self._items.pop()14 # __len__返回项目数 # 被len()函数调用15 def __len__(self) -> int:16 return len(self._items)17 # 创建专门用于整数的Stack# 类型检查器知道栈只保存int18stack: Stack[int] = Stack()# 将整数1压入栈19stack.push(1)# 将整数2压入栈20stack.push(2)# pop返回2(后进先出)21print(stack.pop())运行结果
2
可以用这段代码练习打字。成绩不会计入排行榜。
这段代码中的符号
这段 Python 代码中需要输入的符号及其出现次数。
(× 14)× 14_× 12.× 9:× 8-× 4[× 4]× 4>× 4=× 3