Function annotation of Python functions

Function annotation of Python functions

Overview

The meaning of function annotation is that for the parameters of a custom function, the return value type clearly indicates the data type.
The way to label the data type of the parameters of the function is to follow the parameter name with a colon ":", and specify the type of the parameter after the colon
The way to label the returned data type of the function's return value is: between the function's parameter list and the function's colon, first specify an arrow "–> and specify the data type returned by the function "" after the arrow
The annotation type of the parameters of the function and the return value can be viewed through the function __annotations__
For example, in the function in the following code, the parameter type of the parameter arg0 is a list, arg1, arg2 are both string str, and the return value is also a string str.

def foo(arg0:list, arg1:str, arg2:str='hello,world') -> str:
  print('Annotations:', foo.__annotations__)
  print('arg0 = ', arg0, 'arg1 = ', arg1, 'arg2 = ', arg2)
  print('*' * 50)
  return arg1 + ' and ' + arg2

print(foo([1,2,3], 'test'))

Output:

E:\Python3\Exercise\venv\Scripts\python.exe E:/Python3/Exercise/venv/02.py
Annotations: {
    
    'arg0': <class 'list'>, 'arg1': <class 'str'>, 'arg2': <class 'str'>, 'return': <class 'str'>}
arg0 =  [1, 2, 3] arg1 =  test arg2 =  hello,world
**************************************************
test and hello,world
Process finished with exit code 0

[Previous page] [Next page]

Guess you like

Origin blog.csdn.net/wzc18743083828/article/details/109882790