Answers for "how to copy an object in python"

4

python clone object

import copy

new_ob = copy.deepcopy(old_ob)
Posted by: Guest on December-29-2020
1

python copy variable

>>> import copy
>>> a = 0
>>> b = 2
>>> a = copy.copy(b)
>>> b += 1
>>> a
2
>>> b
3
Posted by: Guest on June-02-2020
0

python copy class object

"""
I've read that there are problems with this approach, but it never let me down
"""

import copy

class Dummy:
    def __init__(self, signature = 1, some_list = []):
        self.signature = signature
        self.list = some_list

    def change_signature(self):
        self.signature += 1

    def change_list(self):
        self.list[0][0] += 1


def naive_test():
    print('---> Naive Copy Test')
    dummy1 = Dummy(1)
    #dummy2 points to dummy1
    dummy2 = dummy1
    if dummy1.signature == dummy2.signature:
        print ('tDummy instances are the same')
    dummy1.change_signature()
    if dummy1.signature == dummy2.signature:
        print ('tDummy 'copy' changed after changing the original. They are still the same.')

def shallow_copy_test():
    print('n---> Shallow Copy Test')
    dummy1 = Dummy(1, [[1,2],[3,4]])
    #Create shallow copy
    dummy2 = copy.copy(dummy1)
    if dummy1.signature == dummy2.signature:
        print ('tDummy instances are the same')
    dummy1.change_signature()
    if dummy1.signature != dummy2.signature:
        print ('tDummy copy didn't change after changing the original. They are now different.')
    dummy1.change_list()
    if dummy1.list == dummy2.list:
        print('tBut their lists change together! This is because the copy only made copies of the original instance's higher level list, but it is a list of lists, so each instance points to two different lists which, in turn, point to the SAME lists')

def deep_copy_test():
    print('n---> Deep Copy Test')
    dummy1 = Dummy(1, [[1,2],[3,4]])
    #Create deep copy
    dummy2 = copy.deepcopy(dummy1)
    if dummy1.signature == dummy2.signature and dummy1.list == dummy2.list:
        print ('tDummy instances are the same')
    dummy1.change_list()
    if dummy1.list != dummy2.list:
        print('tNow each instance is 100% independent. Deep copy goes through all nested references!')


naive_test()
shallow_copy_test()
deep_copy_test()
Posted by: Guest on June-02-2021

Code answers related to "how to copy an object in python"

Python Answers by Framework

Browse Popular Code Answers by Language