我正在嘗試對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
uj5u.com熱心網友回復:
我認為它是 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
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/356474.html
