The default parameters are very useful, but if used incorrectly, they will also fall into the pit. The default parameters have the largest pit, as shown below:
First define a function, pass in a list, add one END
and return:
def add_end(L=[]):
L.append('END') return L
When you call normally, the result seems to be fine:
>>> add_end([1, 2, 3])
[1, 2, 3, 'END']
>>> add_end(['x', 'y', 'z']) ['x', 'y', 'z', 'END']
When you call with default parameters, the result is correct at first:
>>> add_end()
['END']
However, when called again add_end()
, the result is not right:
>>> add_end()
['END', 'END']
>>> add_end()
['END', 'END', 'END']
Many beginners are confused, the default parameter is []
, but the function seems to "remember" the list after the last addition every time 'END'
.
The reasons are explained as follows:
When the Python function is defined, L
the value of the default parameter is calculated, that is []
, because the default parameter L
is also a variable, it points to the object []
, each time the function is called, if L
the content is changed, the default parameter will be called the next time. The content of the function has changed and is no longer what it was when the function was defined []
.
To modify the above example, we can do it with None
this immutable object:
def add_end(L=None):
if L is None: L = [] L.append('END') return L
Now, no matter how many times it is called, there is no problem:
>>> add_end()
['END']
>>> add_end()
['END']
Why design str
, None
such immutable objects? Because once an immutable object is created, the data inside the object cannot be modified, which reduces errors caused by modifying data. In addition, since the object does not change, reading the object at the same time in a multitasking environment does not need to be locked, and there is no problem with reading at the same time. When we write a program, if we can design an immutable object, try to design it as an immutable object