Python(2.7.6) copy - 浅拷贝与深拷贝

时间:2022-09-13 19:48:33

Python 标准库的 copy 模块提供了对象拷贝的功能。 copy 模块中有两个函数 copy 和 deepcopy,分别支持浅拷贝与深拷贝。

copy_demo.py

import copy

class MyClass(object):
    def __init__(self, name):
        super(MyClass, self).__init__()
        self.name = name

a = [MyClass('huey')]
b = copy.copy(a)
c = copy.deepcopy(a)

print 'a is b?', a is b                # a is b? False        
print 'a == b?', a == b                # a == b? True
print 'a is c?', a is c                # a is c? False
print 'a == c?', a == c                # a == c? False

a[0].name = 'sugar'
print 'a[0].name =', a[0].name        # a[0].name = sugar
print 'b[0].name =', b[0].name        # b[0].name = sugar
print 'c[0].name =', c[0].name        # c[0].name = huey