对象的浅复制和深复制

  • 变量的赋值操作

只是形成两个变量,指向的还是同一个对象

  • 浅拷贝

Python的拷贝一般都是浅拷贝,拷贝时,对象包含的子对象不拷贝,因此,原对象和拷贝对象会引用同一个子对象

  • 深拷贝

使用copy模块的deepcopy函数,通过拷贝对象包含的子对象,源对象和拷贝对象所有的子对象也不相同

 

赋值操作:

 1 class MobilePhone:
 2     def __init__(self,cpu,screen):
 3         self.cpu = cpu
 4         self.screen = screen
 5 
 6 class CPU:
 7     def calculate(self):
 8         print('算个12345')
 9         print('cpu对象:',self)
10 
11 class Screen:
12     def show(self):
13         print('显示一个好看的画面')
14         print('screen的对象:',self)
15 
16 c1 = CPU()
17 c2 = c1
18 print(c1)
19 print(c2)

 

 浅对象和深对象

 1 import copy
 2 class MobilePhone:
 3     def __init__(self,cpu,screen):
 4         self.cpu = cpu
 5         self.screen = screen
 6 
 7 class CPU:
 8     def calculate(self):
 9         print('算个12345')
10         print('cpu对象:',self)
11 
12 class Screen:
13     def show(self):
14         print('显示一个好看的画面')
15         print('screen的对象:',self)
16 
17 c1 = CPU()
18 c2 = c1
19 print(c1)
20 print(c2)
21 
22 print('测试浅对象...')
23 s1 = Screen()
24 m1 = MobilePhone(c1,s1)
25 m2 = copy.copy(m1)
26 print(m1,m1.cpu,m1.screen)
27 print(m2,m2.cpu,m2.screen)
28 
29 print('测试深对象...')
30 m3 = copy.deepcopy(m1)
31 print(m1,m1.cpu,m1.screen)
32 print(m3,m3.cpu,m3.screen)