Skip to content

Commit 2d62a3b

Browse files
committed
新增python对象赋值的测试
1 parent 2b29b65 commit 2d62a3b

2 files changed

Lines changed: 74 additions & 0 deletions

File tree

python核心编程日记.md

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -70,3 +70,9 @@ $ sudo su
7070
$ sudo subl /etc/rc.local
7171
在exit 0前面 添加以上两句配置
7272
```
73+
74+
## Python 对象之间赋值
75+
76+
Python 中的对象之间赋值时是按引用传递的,如果需要拷贝对象,需要使用标准库中的 copy 模块。
77+
1. copy.copy 浅拷贝 只拷贝父对象,不会拷贝对象的内部的子对象。
78+
2. copy.deepcopy 深拷贝 拷贝对象及其子对象。

test/test_copy.py

Lines changed: 68 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,68 @@
1+
#!/usr/bin/env python
2+
# encoding: utf-8
3+
4+
"""
5+
@author: zhanghe
6+
@software: PyCharm
7+
@file: test_copy.py
8+
@time: 16-2-17 上午11:07
9+
"""
10+
11+
import copy
12+
13+
14+
def test_01():
15+
"""
16+
测试可变类型对象的拷贝
17+
"""
18+
a = [1, 2, 3, 4, ['a', 'b']] # 原始对象
19+
b = a # 赋值,传对象的引用
20+
c = copy.copy(a) # 对象拷贝,浅拷贝
21+
d = copy.deepcopy(a) # 对象拷贝,深拷贝
22+
23+
a.append(5) # 修改对象a
24+
a[4].append('c') # 修改对象a中的['a', 'b']数组对象
25+
26+
print 'a = ', a
27+
print 'b = ', b
28+
print 'c = ', c
29+
print 'd = ', d
30+
31+
32+
def test_02():
33+
"""
34+
测试不可变类型对象的拷贝
35+
"""
36+
a = [1, 2, 3, 4, 5] # 原始对象
37+
b = a # 赋值,传对象的引用
38+
c = copy.copy(a) # 对象拷贝,浅拷贝
39+
d = copy.deepcopy(a) # 对象拷贝,深拷贝
40+
41+
a[4] = 6 # 修改对象a
42+
43+
print 'a = ', a
44+
print 'b = ', b
45+
print 'c = ', c
46+
print 'd = ', d
47+
48+
49+
if __name__ == '__main__':
50+
test_01()
51+
test_02()
52+
53+
54+
"""
55+
a = [1, 2, 3, 4, ['a', 'b', 'c'], 5]
56+
b = [1, 2, 3, 4, ['a', 'b', 'c'], 5]
57+
c = [1, 2, 3, 4, ['a', 'b', 'c']]
58+
d = [1, 2, 3, 4, ['a', 'b']]
59+
a = [1, 2, 3, 4, 6]
60+
b = [1, 2, 3, 4, 6]
61+
c = [1, 2, 3, 4, 5]
62+
d = [1, 2, 3, 4, 5]
63+
64+
如果对象本身是不可变的,那么浅拷贝时也会产生两个值
65+
顺便回顾下Python标准类型的分类:
66+
可变类型: 列表,字典
67+
不可变类型:数字,字符串,元组
68+
"""

0 commit comments

Comments
 (0)