python clone object
import copy
new_ob = copy.deepcopy(old_ob)
python clone object
import copy
new_ob = copy.deepcopy(old_ob)
python copy instance
import copy
class A(object):
def __init__(self, a)
self.a = a
a = A(38)
# Deepcopy
a2 = copy.deepcopy(a)
# Shallow copy -> use this if copy.deepcopy() fails
a3 = copy.copy(a)
python deepcopy
>>> import copy
>>> nums = [1, 2, 3]
>>> data = {'a': 10, 'b': nums}
>>> data
{'a': 10, 'b': [1, 2, 3]}
>>> data_copy = copy.copy(data)
>>> data_deep = copy.deepcopy(data)
>>> data_copy
{'a': 10, 'b': [1, 2, 3]}
>>> data_deep
{'a': 10, 'b': [1, 2, 3]}
>>> data_copy['a'] += 2
>>> nums[1:1] = [254]
>>> data
{'a': 10, 'b': [1, 254, 2, 3]}
>>> data_copy
{'a': 12, 'b': [1, 254, 2, 3]}
>>> data_deep
{'a': 10, 'b': [1, 2, 3]}
python copy variable
>>> import copy
>>> a = 0
>>> b = 2
>>> a = copy.copy(b)
>>> b += 1
>>> a
2
>>> b
3
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()
Copyright © 2021 Codeinu
Forgot your account's password or having trouble logging into your Account? Don't worry, we'll help you to get back your account. Enter your email address and we'll send you a recovery link to reset your password. If you are experiencing problems resetting your password contact us