Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to assign variable by reference in python? [duplicate]

Tags:

python

It is my vague understanding that python assigns by value. Is there a way to have a python variable assigned by reference? So, that in the below example, it would actually change o.a to 2?

class myClass():
    def __init__(self):
        self.a = 1

    def __str__(self):
        _s = ''
        for att in vars(self):
            _s += '%s, %s' %(att, getattr(self,att))
        return _s


o = myClass()
x = o.a
x = 2
print o
like image 811
chrise Avatar asked Sep 03 '14 08:09

chrise


People also ask

How do you create a duplicate variable in Python?

In Python, we use = operator to create a copy of an object. You may think that this creates a new object; it doesn't. It only creates a new variable that shares the reference of the original object.

How do you assign a reference variable in Python?

However, in Python, variable is just a name given to an object in the memory. Even if we assign its value to another variable, both are in fact referring to same object in memory. This can be verified by id() function. It therefore is clear that in Python, we can not create reference to a variable.

How do you copy instead of reference in Python?

To get a fully independent copy of an object you can use the copy. deepcopy() function.

Does Python copy by value or reference?

Python passes arguments neither by reference nor by value, but by assignment.


1 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 = o.a making the variable x a reference to whatever o.a is (a reference to 1). When you then do x = 2, you are changing what x references (it now references 2, but o.a 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.

like image 172
Tom Dalton Avatar answered Sep 29 '22 15:09

Tom Dalton