-2

I have the following concern in Python:

a = 1
b = a
b = 2
print(a)

From what I understand, b is a new variable that uses the value of a. Thus, when the value of b is changed, that does not affect a. So, print(a) should yield 1.

class Object:
  def __init__(self):
    self.value = 0

a = Object()
a.value = 1
b = a
b.value = 2
print(a.value)

However, in this instance, a would print 2. Why is this? How do I make it so that a.value will still be 1 instead of 2?

Drise
  • 4,310
  • 5
  • 41
  • 66
  • In the first case, you're _rebinding_ `b` (i.e. `b = ...`) to a different object than what `a` is bound to. In the second case, you're _mutating_ the object that both `a` and `b` are bound to. – glibdud Mar 19 '18 at 17:32
  • 1
    You can use `copy.deepcopy()` [Check](https://stackoverflow.com/questions/4794244/how-can-i-create-a-copy-of-an-object-in-python) this answer. – zerek Mar 19 '18 at 17:32
  • 1
    Obligatory reading: https://nedbatchelder.com/text/names.html – chepner Mar 19 '18 at 17:33

1 Answers1

0

If you are running this in cmd, set b = a and then run:

repr(a)
repr(b)
assert(a == b) # is True

They are at the same memory address. Now run:

c = Object() 
repr(c)
assert(a == c) # is False
assert(b == c) # is False

You can see they are different.

Drise
  • 4,310
  • 5
  • 41
  • 66
dfundako
  • 8,022
  • 3
  • 18
  • 34