- 论坛徽章:
- 36
|
回复 2# reyleon
别人python3代码里,搜了一天了,刚提问就在官网翻到了,不过初看不理解做啥的,还有参数后加个:和类型,能解释下有什么意义和用处吗?
4.7.7. Function Annotations
Function annotations are completely optional metadata information about the types used by user-defined functions (see PEP 484 for more information).
Annotations are stored in the __annotations__ attribute of the function as a dictionary and have no effect on any other part of the function. Parameter annotations are defined by a colon after the parameter name, followed by an expression evaluating to the value of the annotation. Return annotations are defined by a literal ->, followed by an expression, between the parameter list and the colon denoting the end of the def statement. The following example has a positional argument, a keyword argument, and the return value annotated:
>>>
>>> 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'
|
|