Functions

Function Annotations

文档:https://docs.python.org/3/tutorial/controlflow.html#function-annotations

1
2
3
4
5
6
7
8
9
10
def f(ham: str, eggs: str = 'eggs') -> str:
print("Annotations:", f.__annotations__)
print("Arguments:", ham, eggs)
return ham + ' and ' + eggs

f('spam')

# Annotations: {'ham': <class 'str'>, 'return': <class 'str'>, 'eggs': <class 'str'>}
# Arguments: spam eggs
# 'spam and eggs'

Type Hints 是 Python3.5 添加的特性,旧版没有
同时还有变量注解:

1
age: int = 20