python

Python 对象拷贝

2017-08-22  本文已影响5人  037251a7c483

Python 赋值只是进行对象的引用。如果拷贝一个对象,则需要使用copy模块。

In [7]: import copy

In [8]: list_obj = [0, 1, 4, [9, 16, 'hello'], 'hello']

In [9]: copy_list = copy.copy(list_obj)

In [10]: deepcopy_list = copy.deepcopy(list_obj)

In [11]: copy_list
Out[11]: [0, 1, 4, [9, 16, 'hello'], 'hello']

In [12]: deepcopy_list
Out[12]: [0, 1, 4, [9, 16, 'hello'], 'hello']


# 赋值是对象引用。
In [13]: assign_list = list_obj

In [14]: assign_list.append('world')

In [15]: list_obj
Out[15]: [0, 1, 4, [9, 16, 'hello'], 'hello', 'world']


# 浅拷贝只拷贝了父对象
# 更改父对象不会改变原对象
# 更改子对象,依然会作用于原对象的子对象
In [16]: copy_list.append("9999")

In [17]: list_obj
Out[17]: [0, 1, 4, [9, 16, 'hello'], 'hello', 'world']

In [18]: copy_list
Out[18]: [0, 1, 4, [9, 16, 'hello'], 'hello', '9999']

In [19]: copy_list[3].append("world")

In [20]: list_obj
Out[20]: [0, 1, 4, [9, 16, 'hello', 'world'], 'hello', 'world']

In [21]: copy_list
Out[21]: [0, 1, 4, [9, 16, 'hello', 'world'], 'hello', '9999']


# 深拷贝不仅会拷贝父对象,也会拷贝子对象。
# 无论是更改父对象还是子对象,都不会作用于原对象
In [22]: deepcopy_list.append(10000)

In [23]: deepcopy_list
Out[23]: [0, 1, 4, [9, 16, 'hello'], 'hello', 10000]

In [24]: list_obj
Out[24]: [0, 1, 4, [9, 16, 'hello', 'world'], 'hello', 'world']

In [25]: deepcopy_list[3].append(10000)

In [26]: deepcopy_list
Out[26]: [0, 1, 4, [9, 16, 'hello', 10000], 'hello', 10000]

In [27]: list_obj
Out[27]: [0, 1, 4, [9, 16, 'hello', 'world'], 'hello', 'world']


上一篇 下一篇

猜你喜欢

热点阅读