Python3提供一种语法,用于为函数声明中的参数和返回值附加元数据,或者也可以称之为注释。
def my_function():
"""
Something about your function…
"""
pass
# 文档注释可以通过下面这种方式查看
print(my_function.__doc__)
言归正传,看代码:
def test(x, y) -> int:
return x + y
上述代码中的 ->int 告诉使用者该函数返回值将会是 int 类型。
也可以给函数参数加上注解,比如:
def func(text:str, max_len:'int>0' = 80) -> str:
pass
text 参数后面加个 : (冒号)接着写类型,如果参数有默认值,则在 : 和 = 之间加上类型。
这些注释信息都是函数的元信息,保存在FuntionName.__annotations__字典中(这里的FunctionName为调用函数名)。
def func(ham: 42, eggs: int = 'spam') -> "Nothing in here":
print("函数注释", func.__annotations__)
print("参数值打印", ham, eggs)
print(type(ham), type(eggs))
func("www")
上面代码运行结果:
函数注释 {'ham': 42, 'eggs': <class 'int'>, 'return': 'Nothing in here'}
参数值打印 www spam
<class 'str'> <class 'str'>