Whether a function parameter in Python is a value or a reference

Source: Internet
Author: User

A straightforward example:

 

1  fromcTYPESImport*2 ImportOs.path3 ImportSYS4 5 defTest (c):6     Print "Test before"7     PrintID (c)8c+=29     Print "Test after +"Ten     PrintID (c) One     returnC A  - defPrintIt (t): -      forIinchRange (len (t)): the         PrintT[i] -  - if __name__=="__main__": -a=2 +     Print "main before invoke test" -     PrintID (a) +n=Test (a) A     Print "main Afterf Invoke test" at     Printa -     PrintID (a)

The results are as follows:

>>>+main afterf invoke test39601564

Conclusion:

Python does not allow programmers to choose whether to use a value or to pass a reference. Python parameter passing is definitely a way to "pass an object reference". This approach is equivalent to a synthesis of the value of the pass and the reference. If a function receives a reference to a mutable object (such as a dictionary or a list), it can modify the original value of the object-the equivalent of passing the object through a "pass reference". If a function receives a reference to an immutable object (such as a number, character, or tuple), it cannot directly modify the original object-the equivalent of passing the object through a "pass value".

Whether a function parameter in Python is a value or a reference

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.