从Python 3.8开始,我就可以做这样的事情:
from typing import TypeVar, Generic
T = TypeVar('T')
class Stack(Generic[T]):
def __init__(self) -> None:
# Create an empty list with items of type T
self.items: List[T] = []
我可以是堆栈[int]或堆栈[str],T可以是任何东西,对吗
但是,如果我想将T的可能值限制为Foo的子类,或者是Foo的子类,并实现BarProtocol呢
Scala有这些漂亮的协方差算子:
T <: Foo, T <: BarProtocol
但是Python中是否有一个等价物
目前没有回答
相关问题 更多 >
编程相关推荐