我试图理解类型注释,我有以下代码:
from typing import TypeVar
T = TypeVar('T')
class MyClass():
x: int = 10
def foo(obj: T) -> None:
print(obj.x)
foo(MyClass())
Run Code Online (Sandbox Code Playgroud)
当我运行 mypy 时,出现以下错误:
main.py:9: error: "T" has no attribute "x"
Found 1 error in 1 file (checked 1 source file)
Run Code Online (Sandbox Code Playgroud)
但是当我添加bound='MyClass'到时TypeVar,它没有显示任何错误。
这种行为的原因是什么?我尝试阅读文档,但没有找到任何关于bound设置为默认值时到底发生了什么的答案。