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

 

相关文章:

  • 2021-11-24
  • 2021-07-02
  • 2022-01-04
  • 2021-07-26
  • 2021-10-05
猜你喜欢
  • 2021-05-19
  • 2021-09-09
  • 2021-12-22
  • 2022-02-09
相关资源
相似解决方案