First question about Liao Xuefeng's python Tutorial: Liao Xuefeng's python tutorial
Function parameters are described in the section:
Def add_end (L = []);
L. append ('end ')
Return L
When add_end is called normally (that is, when parameter data transmission is available ):
>>> Add_end ([1, 2, 3]) [1, 2, 3, 'end'] >>> add_end (['x', 'y ', 'Z']) ['x', 'y', 'z', 'end']
When default parameters are used:
>>> add_end()['END']
>>> add_end()['END', 'END']>>> add_end()['END', 'END', 'END']
Liao Xuefeng explained the following:
When defining a Python function, the default parameterL
Is calculated, that is[]
Because the default parametersL
It is also a variable that points to the object[]
. If this function is called every timeL
The content of the default parameter changes next time, instead of when the function is defined.[]
.
My understanding is as follows:
In the first line, input the parameter [, 3]. The following code is for [, 3]. It has nothing to do with L = []. The third line is the same as the first line, L = [] is not involved in these two times, so the value of L remains unchanged. The second line does not include parameters, so the following code is for L, from [] to ['end'], and the fourth line is for L, however, the value of L has been changed to ['end'] and is run again, so it becomes ['end', 'end'].
The improvement method is as follows:
def add_end(L=None): if L is None: L = [] L.append('END') return L
>>> add_end()['END']>>> add_end()['END']
But I still don't understand the sentence if L is None: L = []. I hope I can understand it later.