Skip to content

Commit ca9233b

Browse files
committed
赋值、浅拷贝、深拷贝
1 parent 657f371 commit ca9233b

File tree

4 files changed

+73
-0
lines changed

4 files changed

+73
-0
lines changed

exercise/assign_test.py

+23
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
# 变量的赋值
2+
3+
class CPU:
4+
pass
5+
6+
7+
class Disk:
8+
pass
9+
10+
11+
class Computer:
12+
def __init__(self, cpu, disk):
13+
self.cpu = cpu
14+
self.disk = disk
15+
16+
17+
# 变量的赋值操作,只是形成两个变量,实际上还是指向同一个对象
18+
cpu1 = CPU()
19+
cpu2 = cpu1
20+
print(cpu1)
21+
print(id(cpu1))
22+
print(cpu2)
23+
print(id(cpu2))

exercise/deep_copy_test.py

+25
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
import copy
2+
3+
4+
# 深拷贝
5+
class CPU:
6+
pass
7+
8+
9+
class Disk:
10+
pass
11+
12+
13+
class Computer:
14+
def __init__(self, cpu, disk):
15+
self.cpu = cpu
16+
self.disk = disk
17+
18+
19+
cpu = CPU()
20+
disk = Disk()
21+
computer = Computer(cpu, disk)
22+
# 深拷贝:不仅拷贝源对象,也递归拷贝子对象
23+
computer2 = copy.deepcopy(computer)
24+
print(computer, computer.cpu, computer.disk)
25+
print(computer2, computer2.cpu, computer2.disk)
Loading

exercise/shallow_copy_test.py

+25
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
import copy
2+
3+
4+
# 浅拷贝
5+
class CPU:
6+
pass
7+
8+
9+
class Disk:
10+
pass
11+
12+
13+
class Computer:
14+
def __init__(self, cpu, disk):
15+
self.cpu = cpu
16+
self.disk = disk
17+
18+
19+
cpu = CPU()
20+
disk = Disk()
21+
computer = Computer(cpu, disk)
22+
# 浅拷贝:只拷贝源对象,不拷贝子对象
23+
computer2 = copy.copy(computer)
24+
print(computer, computer.cpu, computer.disk)
25+
print(computer2, computer2.cpu, computer2.disk)

0 commit comments

Comments
 (0)