Python: Optional and parameters with default values

Parameters with default values

In a class or function in Python, if a parameter is declared with its default value, you can optionally assign a value to the parameter when instantiating or calling, for example:

#默认值参数
def foo_v1(a: int, b: int = 1):
    print(a + b)
#未给b传入实参时,采用默认值    
foo_v1(2)

# 输出
# >>> 3

[ Note: When specifying the default value, it is not necessary to declare the type of the variable (after all, the object and variable name in Python are just a pointer or address). Python is a dynamic language, and it will always be in the Python interpreter process When running, dynamically determine the type of a variable assignment, and the reason why the static type is declared in the code is to reduce human errors and provide corresponding types or error prompts, but it will not affect the operation of Python !

Typing.Optional class

The optional type is almost equivalent to a parameter with a default value . The difference is that using Optional will tell your IDE or framework: this parameter can be None in addition to the given default value, and use some static checking tools such as mypy When using a: int = None, a similar statement may prompt an error, but using a: Optional[int] = None will not.

The following is an explanation of it from the Python Documents:insert image description here

Optional[X] is equivalent to Union[X, None]

Look at an example:

#Optional
from typing import Optional

def foo_v2(a: int, b: Optional[int] = None):
    if b:
        print(a + b)
    else:
        print("parameter b is a NoneType!")

#只传入a位置的实参
foo_v2(2)

# 输出
>>> parameter b is a NoneType!

When you give the optional parameter a default value other than None, take a look at the hints that Optional brings to the IDE:

insert image description here

This means that b is an optional parameter in this function , and you are prompted that its default value can be None.

Guess you like

Origin blog.csdn.net/qq_44683653/article/details/108990873
Recommended