6

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
chrise
  • 4,039
  • 3
  • 39
  • 74

2 Answers2

5

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.

Tom Dalton
  • 6,122
  • 24
  • 35
  • so, I take it there is now way to make x a reference to o.a instead of the value of o.a? – chrise Sep 03 '14 at 10:07
  • There's no way to make x change whenever o.a changes, unless you make them both refer to the same mutable object (e.g. a list), and then modify that object (e.g. change the contents of that list). – Tom Dalton Sep 03 '14 at 11:52
1

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

You cannot change this.

If you want to change o.a 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 = o.a' 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 o.a since x and o will reference to the same instance.

Michel Keijzers
  • 15,025
  • 28
  • 93
  • 119