how to assign variable by reference in python?

This question already has an answer here:

  • How do I pass a variable by reference? 23 answers

  • The simple answer is that all variables in python are references. Some references are to immutable objects (such as strings, integers etc), and some references are to mutable objects (lists, sets). There is a subtle difference between changing a referenced object's value (such as adding to an existing list), and changing the reference (changing a variable to reference a completely different list).

    In your example, you are initially x = oa making the variable x a reference to whatever oa is (a reference to 1 ). When you then do x = 2 , you are changing what x references (it now references 2 , but oa still references 1 .

    A short note on memory management:

    Python handles the memory management of all this for you, so if you do something like:

    x = "Really_long_string" * 99999
    x = "Short string"
    

    When the second statement executes, Python will notice that there are no more references to the "really long string" string object, and it will be destroyed/deallocated.


    Actually, it depends on the type. Integers, floats, strings etc are immutable, eg instances of objects are mutable.

    You cannot change this.

    If you want to change oa you need to write:

    o.a = 2
    

    In your case

    x = 2
    

    Makes just a new variable with value 2 and is unrelated to the 'x = oa' statement above (meaning the last statement has no effect).

    What would work is:

    x = o
    

    This will make a reference to o. And than say

    x.a = 2
    

    This will also change oa since x and o will reference to the same instance.

    链接地址: http://www.djcxy.com/p/20840.html

    上一篇: 在python中通过ref / by ptr发送?

    下一篇: 如何在python中通过引用分配变量?