Parameter passing and return values in Python

Source: Internet
Author: User

Parameter passing in Python is similar to Java, with its own memory-recycling mechanism, which differs greatly from C + +.

1. Parameter passing of the function:

>>> a = [123]>>> def Fun (a):        for in  A:            print I
A.append (4)>>> fun (a)12344807792> >> a[1234]

As you can see from the above results, Python's function passing is a reference pass, so modifying the object content inside the function causes the object content to change outside the function.

This is not true for some built-in types, such as int,float.

Note that if you do a del operation within a function for a passed in parameter, it will not affect the actual object, because del deletes the reference, and the actual object has a reference count of at least 1, so it will not be recycled.

2. Return of function:

>>> def Fun ():        = [123]        print ID (a)        return  a>>> a = Fun ()44806192>>> ID (a)44806192 
>>> def Fun ():        1        Print ID (a)        return  a>> > A = Fun ()34243104>>> ID (a)34243104

As you can see, the function returns a reference to the object, and the object now has a reference count of 1, so it is not reclaimed by memory.

This is definitely a mistake in C + +, but Python has its own memory-recycling mechanism, so it's no problem.

3. Summary:

Python is similar to Java in that there is no pointer to an object, and each object is manipulated by reference, so that when the function is passed and the function returns, the action on the same object is implemented by a reference to the same object. When the function call ends, the memory of the object does not disappear, but the reference itself is recycled.

Parameter passing and return values in Python

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.