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
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.
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.
To get a fully independent copy of an object you can use the copy. deepcopy() function.
Python passes arguments neither by reference nor by value, but by assignment.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With