import copy
class MobilePhone(object):
def __init__(self, cpu, screen):
self.cpu = cpu
self.screen = screen
class CPU(object):
def calculate(self):
print("算你个123456")
print("cpu对象:", self)
class Screen(object):
def show(self):
print("显示一个好看的画面,亮瞎你的钛合金大眼")
print("screen对象:", self)
# 变量赋值,只是引用,不是copy
c1 = CPU()
c2 = c1
print(c1)
print(c2)
print(id(c1))
print(id(c2))
print()
# 浅copy
s = Screen()
m1 = MobilePhone(c1,s)
m2 = copy.copy(m1)
print(m1, m1.cpu, m1.screen)
print(m2, m2.cpu, m2.screen)
print(id(m1), id(m1.cpu), id(m1.screen))
print(id(m2), id(m2.cpu), id(m2.screen))
print()
# 深copy
m3 = copy.deepcopy(m1)
print(m1, m1.cpu, m1.screen)
print(m3, m3.cpu, m3.screen)
print(id(m1), id(m1.cpu), id(m1.screen))
print(id(m3), id(m3.cpu), id(m3.screen))
"""
执行结果:
<__main__.CPU object at 0x0000022B9E158470>
<__main__.CPU object at 0x0000022B9E158470>
2386359059568
2386359059568
<__main__.MobilePhone object at 0x0000022B9E158EF0> <__main__.CPU object at 0x0000022B9E158470> <__main__.Screen object at 0x0000022B9E158FD0>
<__main__.MobilePhone object at 0x0000022B9E165518> <__main__.CPU object at 0x0000022B9E158470> <__main__.Screen object at 0x0000022B9E158FD0>
2386359062256 2386359059568 2386359062480
2386359112984 2386359059568 2386359062480
<__main__.MobilePhone object at 0x0000022B9E158EF0> <__main__.CPU object at 0x0000022B9E158470> <__main__.Screen object at 0x0000022B9E158FD0>
<__main__.MobilePhone object at 0x0000022B9E165550> <__main__.CPU object at 0x0000022B9E173EF0> <__main__.Screen object at 0x0000022B9E173F98>
2386359062256 2386359059568 2386359062480
2386359113040 2386359172848 2386359173016
Process finished with exit code 0
"""
参考视频