相关疑难解决方法(0)

TypeVar('T', A, B) 和 TypeVar('T', bound=Union[A, B]) 的区别

我正在努力弄清楚以下两个TypeVars之间的区别

from typing import TypeVar, Union

class A: pass
class B: pass

T = TypeVar("T", A, B)
T = TypeVar("T", bound=Union[A, B])
Run Code Online (Sandbox Code Playgroud)

有人想启发我吗?

一个我不明白的例子......

T = TypeVar("T", bound=Union[A, B])

class AA(A):
    pass


class X(Generic[T]):
    pass


class XA(X[A]):
    pass


class XAA(X[AA]):
    pass
Run Code Online (Sandbox Code Playgroud)

通过类型检查,但T = TypeVar("T", A, B)失败了

错误:“X”的类型变量“T”的值不能是“AA”

相关:this question on the difference between Union[A, B]andTypeVar("T", A, B)

python generics type-hinting

16
推荐指数
2
解决办法
5440
查看次数

标签 统计

generics ×1

python ×1

type-hinting ×1