0

I would like to change the value of a member of an object. I can do this as long as i adress the object itself. However when I store a reference to this member it doesn't work. Instead it changes the reference object.

class MyClass:
    def __init__(self, name):
        self.a = 1
        self.b = name

obj1=MyClass("string")
refob1=obj1.a
refob2=obj1.b

#I can change my object like this:
obj1.a=99
obj2.b="changed"


#But not like this:
refob1 = 1
refob2 = "changed_reference"

How can I use the reference object to change the members?

Benjamin
  • 298
  • 1
  • 12
  • This is not special to instances. You'd get the same with `foo = 3`, `fooref = foo`, `foo = 4`. You rebound a name to point to a new object, so `fooref` is no longer going to see that change. – Martijn Pieters May 18 '17 at 09:34

1 Answers1

2

This is because int and strings in python are non-mutable objects. This means that they pass a copy of the value instead of the reference.

lists, in the other hand, are mutable objects and allow your desired behavior. Here you have an example:

class MyClass(object):
    def __init__(self):
        self.a = 3
        self.b = [1]

obj = MyClass()
outside_a = obj.a
outside_a = 3 # outside_a is just a copy of obj.a value, so it won't change obj object
outisde_b = obj.b
outside_b[0] = 3 # Lists are mutabe, so this will change obj.b value
print obj.b # Prints [3]

So, how can you go around this? It is a bit ugly, but you can use a container (list) to contain the variables you want to reference later on. Here you can find a related post: Python passing an integer by reference

Community
  • 1
  • 1
Carles Mitjans
  • 4,786
  • 3
  • 19
  • 38