变量使用注释进行注释:
x = 3 # 类型:int x = negate(x) x = 'a type-checker might catch this error'
从Python 3.6开始,还有用于变量注释的新语法。上面的代码可能使用以下形式
x: int = 3
与注释不同的是,还可以将类型提示添加到先前未声明的变量中,而无需为其设置值:
y: int
另外,如果在模块或类级别使用了这些,则可以使用以下方式检索类型提示:typing.get_type_hints(class_or_module)
class Foo:
x: int
y: str = 'abc'
print(typing.get_type_hints(Foo))
# ChainMap({'x': <class 'int'>, 'y': <class 'str'>}, {})或者,可以使用__annotations__特殊变量或属性来访问它们:
x: int
print(__annotations__)
# {'x': <class 'int'>}
class C:
s: str
print(C.__annotations__)
# {'s': <class 'str'>}