注解是以字典形式存储在函数的__annotations__中。
参数的注解是定义在参数名称的冒号后面,紧随着一个用来表示注解的值的表达式。
返回注释是定义在一个->后面,紧随着一个表达式,在冒号与->之间。
下面的示例包含一个位置参数,一个关键字参数,和没有意义的返回值注释:
def
f
(
ham
:
42
,
eggs
:
int
=
'spam'
)
->
"
Nothing to see here
"
:
print
(
"Annotations:"
,
f
.
__annotations__
)
print
(
"Arguments:"
,
ham
,
eggs
)
f
(
'wonderful'
)
----
Annotations: {'eggs': <class 'int'>, 'return': 'Nothing to see here', 'ham': 42}
Arguments: wonderful spam
注:
第一行蓝色部分是注释。eggs是关键字参数。