Article directory
Parameters with default values
In a class or function in Python, if a parameter is declared with its default value, the parameter can be optionally assigned a value when instantiated or called, 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 (in the final analysis, the object and variable name in Python are just a pointer or an address), Python is a dynamic language, it will always be in the Python interpreter process. Dynamically determine the type of a variable assignment at runtime, and the reason for declaring a static type in the code is to provide the corresponding type or error prompt to reduce human errors, but it will not affect the operation of Python! 】
Typing.Optional class
Optional type, the function is almost equivalent to the parameter with 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 , similar declarations such as a: int = None may prompt an error, but using a :Optional[int] = None will not.
Optional[X] is equivalent to Union[X, None]
See 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 default value of the Optional parameter is not None, look at the hint that Optional brings to the IDE:
it means that b is an optional parameter in this function, and you are prompted that its default value can be None.