Look at a piece of code first
I=5def Test (arg=i): Print (ARG) i=6test ()
Testing, the result is 5, which is not the same as the general programming language results. According to Python, the function default value can only be assigned once, that is, the first arg is assigned a value of 5, it will no longer be assigned, although before running the function I was assigned a value of 6, do not know that this understanding is correct, this should be noted, it is easy to error.
Next section of code
def test (i,l=[]): L.append (i) Print (l) test (1) test (2) test (3)
After the test results are
[1] [1, 2] [1, 2, 3]
This result is not the same as most programming languages, because the variable is initially an empty list, and if no definition is given in the function call, then the arguments passed to it are accumulated (in front) during the subsequent call.
This is a more in-depth answer:
For the traditional language, the above code will be executed in the memory to declare a variable p, and then put 1 in the memory of the variable p. When the addition operation is performed, a 2 result is obtained, and the value of 2 is deposited again in the memory address of P. Visible in the entire execution process, the change is the value of the memory address where the variable p is located
In this code, Python actually creates a 1 object in memory now and points p to it. When the addition operation is performed, a new object of 2 is actually obtained through the addition operation, and P points to the new object. Visible in the entire execution process, the change is the memory address that P points to
If you want to avoid this situation, either do not use the object that can be changed as the default parameter, or
def test (I, L=none): if L is none:l = [] L.append (i) return L
This article is from "Deast's Nest" blog, please make sure to keep this source http://xudongdong.blog.51cto.com/1889083/1981980
Some questions about the Python function