0

(In python) I want to be able to write something like a + b, and so that as a result a has the value of the sum of a and b, also so that id(a) does not change (that is, change data at the address of a variable in memory rather than create a new address with the result of the sum and refer to it with a).

My attempt to use += fails:

a, b = 5, 6
start_id = id(a)
a += b
print(start_id == id(a))
# Outputs: False
0dminnimda
  • 1,242
  • 3
  • 12
  • 29

2 Answers2

0

In python pass reference only for objects. If you want do such a thing you need to create an object that represent your integer

You can also cheat a bit the system by taking the scope of the program when calling the function

def function(a,b, scope=locals()):
  var_name = [key for key, value in scope.items() if value == a][0]
  scope[var_name] += b


a = 4
b = 5
function(a, b)
print(a) #output 9

Note that here the result will be bound to the first variable with the same value of a which could be a big anoyement.

Xiidref
  • 1,456
  • 8
  • 20
0

want to make such an addition function (example of use: "a + b"), which will modify a and not return anything (In Python)

When doing this within a function you cannot simply use a += b because a would be treated as local variable which is not defined. Therefore you need to explicitly tell that you want to use the global variable a:

def add_to_a(val):
   global a
   a += val

a = 42
b = 1
add_to_a(b)

Since the actual question is now why id changes after changing the value of a the answer is: Because integres are immutable in python and you have to work around that - like in the answers in this question

Odysseus
  • 1,213
  • 4
  • 12