0

I have an instance of a class that I want to save in a different variable, so that I can make changes to the original without the state stored in the other variable being affected.

However, any changes I make to the original object (nn) is replicated in the second object (nn_2).

Code:

nn_2 = nn
nn_2.LEARNING_RATE = 3
nn.LEARNING_RATE = 1
print(nn_2.LEARNING_RATE)
print(nn.LEARNING_RATE)

Output:

1
1

What would be the way of achieving this?

Thanks,

Hamid
  • 81
  • 1
  • 12
  • Thanks for this! I was searching how to save an instance rather than copy which is probably why I couldn't find the answer. – Hamid Mar 20 '17 at 17:34

1 Answers1

0

You should use copy.deepcopy() to copy objects so that it doesn't link to the same object.

from copy import deepcopy

nn_2 = deepcopy(nn)
nn_2.LEARNING_RATE = 3
nn.LEARNING_RATE = 1
print(nn_2.LEARNING_RATE)
print(nn.LEARNING_RATE) # should be different now
Taku
  • 31,927
  • 11
  • 74
  • 85