"bound" 中的参数 typing.TypeVar 是什么意思?

what does argument "bound" mean in typing.TypeVar?

所以我正在尝试学习打字模块,但我完全卡在了 bound= 部分。 我读过 this 综合主题好几遍了,但由于我是新手,所以不太了解。

能否请您解释一下 bound= 的用途以及上限是什么意思? (最好是一个简单的例子)

先谢谢你!

所以 the documentation 关于这个主题有点神秘,特别是如果您是初学者。让我们举个例子:

class Foo:
    pass


class Bar(Foo):
    pass


T = TypeVar("T", bound=Foo)


def foo_bar(x: T):
    print(x)


foo_bar(Bar()) # valid

此处的 bound 参数表示 class 的任何实例继承 Foo 或其任何子 classes 验证用 [= 定义的类型标准13=].