首页 > 代码库 > 深浅拷贝

深浅拷贝

#!/usr/bin/env python
# -*- coding:utf-8 -*-

import copy

# 字符串和数字浅拷贝等价于n2 = n1
n1 = 123
n2 = copy.copy(n1)
print(id(n1))
print(id(n2))

n1 = [‘aa‘, ‘bb‘, [‘cc‘, ‘dd‘]]
n2 = copy.copy(n1)
# 相同
print(id(n1[2]))
print(id(n2[2]))
assert (id(n1[2]) == id(n2[2]))

n2 = copy.deepcopy(n1)
# 不同
print(id(n1[2]))
print(id(n2[2]))
assert not (id(n1[2]) == id(n2[2]))

 

深浅拷贝