有限制的Python泛型?

2024-09-30 04:40:32 发布

您现在位置:Python中文网/ 问答频道 /正文

从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中是否有一个等价物


Tags: fromimportselftypingfoostack堆栈def

热门问题