When defining a Python function, keep in mind one thing when defining default parameters: default parameters must point to immutable objects!

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 ENDand 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, Lthe value of the default parameter is calculated, that is [], because the default parameter Lis also a variable, it points to the object [], each time the function is called, if Lthe 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 [].

One thing to keep in mind when defining default parameters: default parameters must point to immutable objects!

To modify the above example, we can do it with Nonethis 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, Nonesuch 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

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324491452&siteId=291194637