In python, as the default parameter must be immutable object, if it is a mutable object, there will be problems, a little attention, will be transferred into traps, especially beginners, such as I (┬_┬).
Let's look at an example.
1 defAdd (l=[]):2L.append (1)3 returnL4 5L = [1, 2, 3]6NEWL =Add (L)7 Print(NEWL)8NEWL =Add (NEWL)9 Print(NEWL)Ten OneTestl =Add () A Print(TESTL) -Testl =Add () - Print(TESTL) theTestl =Add () - Print(TESTL)
Run results
When the parameters are passed in normally, there seems to be no big problem. But when we use the default parameters, the problem arises.
The results of the operation did not appear as we expected. Why?
When we call a function, if there is a pass parameter, the passed argument is used, and if no argument is passed, the default argument is used. when using default parameters, the same is used, that is, the last default parameter value saved. We can verify this by printing the ID.
Therefore, the default parameter must be immutable , and if it is a mutable object, this will happen.
So how to solve it?
We can let L point to the immutable variable of None, and then add a judgment to let the default parameter return to the position .
1 defAdd (l=None):2 if(L = =None):3L = []4L.append (1)5 returnL6 7L = [1, 2, 3]8NEWL =Add (L)9 Print(NEWL)TenNEWL =Add (NEWL) One Print(NEWL) A -Testl =Add () - Print(TESTL) theTestl =Add () - Print(TESTL) -Testl =Add () - Print(TESTL)
This way, we solve the trap, then next time should not fall into the, you say?
Remember: The default parameter is to use immutable objects!!!
Immutable (immutable):int,string,float, number,tuple
Variable (mutable):dictionary,list,set
A list in Python as a default parameter trap