Analysis of default parameter instances in Python and Analysis of python parameter instances
This article focuses on the Content of default parameters in Python.
If you are familiar with the C ++ language, you can know that the default parameters in the C ++ language are written in the function declaration, which is a syntactic sugar and has nothing to do with function calls, it is called by the compiler when the function is called.
The default parameters in Python are quite different from those in Python. What is the result of code execution in the following example?
def test_parameter(a, dfp=[]): dfp.append(a) print(dfp)test_parameter(1)test_parameter(2)test_parameter(3)
The result is as follows, which is totally different from our expectation:
[1][1, 2][1, 2, 3]
Analysis
Why does Python's default parameters look like this? You need to start with the Python function definition. In Python, def is actually an executable statement. When def is executed, a function object is created, the default parameters are calculated when the def statement is executed and exist in the _ defaults _ attribute of the function.
def test_parameter(a, dfp=[]): dfp.append(a) print(id(dfp))test_parameter(1)test_parameter(2)print(test_parameter.__defaults__)print(id(test_parameter.__defaults__[0]))
The result is as follows. The default parameter used to call a function is the same as the object in _ defaults:
140109485401224140109485401224([1, 2],)140109485401224
Use
After understanding the above principles, you can know that you need to pay attention to the use of default parameters in the future, if the default parameter is a mutable object, you need to determine whether to share the default parameter or generate a new object each time a function is called. If the new object is generated, None is often used as the default parameter placeholder. If the current value is None, the new variable object is used.
Def test (a, dfp = None): if dfp is None: dfp = [] pass # Use dfp
Summary
The above is all about the analysis of default parameter instances in Python. I hope it will be helpful to you. If you are interested, you can continue to refer to other related topics on this site. If you have any shortcomings, please leave a message. Thank you for your support!