Some questions about the Python function

Source: Internet
Author: User
Tags diff

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.