python - 泛型类型 T 的 Python 子类列表
问题描述
我正在尝试继承list
泛型类型T
。现在,我可以通过多重继承来实现我想要的,Generic
如下list
所示。有没有更好的方法来实现同样的目标?
from typing import TypeVar, Generic
T = TypeVar('T')
class SuperList(Generic[T], list):
def __init__(self, *args: T):
super().__init__(args)
def really_awesome_method(self):
...
class A(SuperList[int]):
pass
class B(SuperList[str]):
pass
解决方案
我认为它是 3.9 中的新功能,但您可以下标许多内置容器来创建泛型类型别名。所以你应该能够做到:
class SuperList(list[T]):
def __init__(self, *args: T):
super().__init__(args)
class A(SuperList[int]):
pass
https://docs.python.org/3/library/stdtypes.html#types-genericalias
推荐阅读
- ajax - 从 Ajax 保存到子目录的文件上传
- bash - 如何根据目录名称重命名子目录中的文件
- powershell - 与file2比较时如何更新文件中的行
- swift - 当 UITextField.secureTextEntry 改变它的值时,Swift 得到回调
- python - 比较和附加不同长度的python列表
- go - 使用 Goroutine 订阅 MQTT 消息
- macos - 如何在我的 macOS El Capitan 上找到或制作 python 的可执行文件
- java - 如何正确使用Condition等待和notifyAll而不丢失通知?
- javascript - 如何使用 Google Place Geocomplete 获得英文搜索结果?
- python - 如何将base64字符串解码为其原始图像并打开它而不保存它