1

I would like to achieve the same behaviour you get when copying mutable variables in python with an immutable integer. Such as follows:

>>>b = [3,4]
>>>a = b
>>>a
[3,4]
>>>b.append(2)
>>>b
[3,4,2]
>>>a
[3,4,2]

But instead of lists, I have something as follows:

>>>b = 3
>>>a = b
>>>a
3
>>>b += 1
>>>b
4
>>>a
3

Which is not what I want, I would ideally like a to update to the new value of b, which is 4. So essentially a pointer.

How would I achieve this in python?

Recessive
  • 1,780
  • 2
  • 14
  • 37
  • 5
    ints are immutable in python so what youre looking for is not possible. – The BrownBatman Jul 09 '19 at 03:55
  • you can't do it directly, but you could make a class that holds an integer; then, as in your example, different variables can reference the same instance. – jdigital Jul 09 '19 at 03:56
  • 1
    Why do you want to do this? If you can explain your reasons for wanting this behaviour, perhaps we can suggest some alternatives. – Paritosh Singh Jul 09 '19 at 04:13
  • https://stackoverflow.com/questions/1135335/increment-int-object check this out – Pratik Jul 09 '19 at 04:58
  • @ParitoshSingh It's not critical, just a matter of ease of use. I have a structural object, that I would like to be able to reference a property of one of the objects it works as a "container" for, ie: `class struct():...`, `class segment():...`, where `segment` has property `speed`, and so would like to be able to do `struct.speed`, and have it return `segment.speed`. But obviously simply equating the two doesn't work, as integers are immutable. – Recessive Jul 09 '19 at 05:15
  • @TheBrownBatman Thanks for clarification. I thought maybe it was just something I'd missed. – Recessive Jul 09 '19 at 05:16

1 Answers1

-1

As there is no concept of the pointer in python, but you can use an alternative way to get your result by making function:-

b = 5
a = b
def update():
    global a,b
    b+=1
    a+=1

update()  # Call this function whenever you want to update the value of b AND a.
print(f"New value of a is {a}")
print(f"New value of b is {b}")

Output

New value of a is 6
New value of b is 6

I hope it may help you.

Rahul charan
  • 765
  • 7
  • 15
  • This is restricted to the hard coded values in the function. I need something flexible to any and all values. – Recessive Jul 09 '19 at 05:15