import copy
from filecmp import cmp
class MyClass:
def __init__(self, name):
self.name = name
def __cmp__(self, other):
return cmp(self.name, other.name)
a = MyClass('a')
myList = [a]
shallow_copy = myList.copy()
print('myList: ', myList)
print('shallow_copy: ', shallow_copy)
print('shallow_copy is myList: ', (shallow_copy is myList))
print('shallow_copy == myList: ', (shallow_copy == myList))
print('shallow_copy[0] is myList[0]: ', (shallow_copy[0] is myList[0]))
print('shallow_copy[0] == myList[0]', (shallow_copy[0] == myList[0]))
print("*"*20)
deep_copy = copy.deepcopy(myList)
print('myList: ', myList)
print('deep_copy: ', deep_copy)
print('deep_copy is myList: ', (deep_copy is myList))
print('deep_copy == myList: ', (deep_copy == myList))
print('deep_copy[0] is myList[0]: ', (deep_copy[0] is myList[0]))
print('deep_copy[0] == myList[0]', (deep_copy[0] == myList[0]))
运行结果:
myList: [<__main__.MyClass object at 0x0000000002617EB0>]
shallow_copy: [<__main__.MyClass object at 0x0000000002617EB0>]
shallow_copy is myList: False
shallow_copy == myList: True
shallow_copy[0] is myList[0]: True
shallow_copy[0] == myList[0] True
********************
myList: [<__main__.MyClass object at 0x0000000002617EB0>]
deep_copy: [<__main__.MyClass object at 0x00000000026BB430>]
deep_copy is myList: False
deep_copy == myList: False
deep_copy[0] is myList[0]: False
deep_copy[0] == myList[0] False