首页 > 解决方案 > 泛型类型 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

标签: pythonpython-3.xlistgenericssubclass

解决方案


我认为它是 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


推荐阅读