After Python function parameters in the colon statement Yes -> arrow

When the function declaration python3.7 environmental parameters can be added in the colon, as shown:

 def f(ham: str, eggs: str = 'eggs') -> str :
     print("Annotations:", f.__annotations__)
     print("Arguments:", ham, eggs)
     return ham + ' and ' + eggs
 
 print(f("test","abc"))

May be questioned, python is not a dynamically typed language, do the authors also specify the parameter type?

Look at the print results:
Here Insert Picture Description
it also can really pass other types of values, such as: f ( "test", 123 )

That result? As follows:
Here Insert Picture Description
course error, ah, the return value is a string, int type can not participate in string concatenation, that after writing a parameter: str and -> str What does it mean?

PS: If necessary Python learning materials can be added to a small partner click the link below self-acquire
note.youdao.com/noteshare?id=2dce86d0c2588ae7c0a88bee34324d76

Indicated in the official document .__ annotations__ is a function of the parameters and return values ​​Comment Comment:

Therefore, print out Annotations: { 'ham': <class 'str'>, 'eggs': <class 'str'>, 'return': <class 'str'>}

In fact, it did not specify the type of people just write function with the function of reminding people what the best type of parameters passed, because the last two parameters need to be string concatenation;

Of course, you can also write directly to the string reminder:

def f(ham: "传一个字符串", eggs: str = 'eggs') -> str :
    print("Annotations:", f.__annotations__)
    print("Arguments:", ham, eggs)
    return ham + ' and ' + eggs

print(f("test",123))

And that arrow after the function declaration: "->" is the return value of the Notes, -> str that is meant to remind the user function return value is a str type.

Guess you like

Origin www.cnblogs.com/python960410445/p/11960460.html