Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make copy of object instance in Python [duplicate]

Tags:

python

oop

I would like to make a copy of a python class object which does not change when the original object changes. Here is my simple working example:

class counterObject:
    def __init__(self):
        self.Value = 0

    def incrementValue(self):
        self.Value += 1

    def printValue(self):
        print(self.Value)

A = counterObject()
A.incrementValue()
A.printValue() #Prints 1

B = A
A.incrementValue()
B.printValue() #Currently prints 2. Want to be 1

From my understanding, when I set B = A, this just means B points to the object A. Hence when I change A it changes B as well. Is it possible to instead make B a new instance with all the same properties as A, but does not change when I change A? In my above example, I would like the value for B to stay at 1 when I increment A.

If A and B were lists instead of objects I would write B = list(A). I guess I am asking if there is a similar method for class objects?

Thank you in advance for your help!

like image 487
sean ericson Avatar asked Dec 18 '22 09:12

sean ericson


1 Answers

If you want to make a copy then one way is using deepcopy:

from copy import deepcopy
B = deepcopy(A)

All = does is to assign another reference to the same object in memory. The deepcopy creates a whole new object in memory with the values of A and B will reference it. if you do the following you will see different prints:

B = A
print( id(A), id(B)) # Same ids

B = deepcopy(A)
print( id(A), id(B) # Different ids
like image 105
Gilad Green Avatar answered Jan 13 '23 20:01

Gilad Green