变量的赋值操作
只是形成两个变量,实际还是指向同一个对象。
浅拷贝
Python 拷贝一般都是浅拷贝。拷贝时,对象包含的子对象内容不拷贝。因此,源对象和拷贝对象会引用同一个子对象。
深拷贝
使用 copy 模块的 deepcopy 函数,递归拷贝对象中包含的子对象。源对象和拷贝对象所有的子对象也不同。
【示例】手机对象里有cpu和screen。将手机拷贝,测试里面的cpu和screen是否变化。
'''
测试下深 浅拷贝
'''
import copy
class MobilePhone:
def __init__(self,cpu,screen):
self.cpu = cpu
self.screen =screen
class Cpu:
def cpu_name(self):
print("我的型号是:高通的")
class Screen:
def show(self):
print("地有多圆,天有多方,我就可以展示多莫精彩!")
c = Cpu()
s = Screen()
print("测试浅拷贝。。。")
m1 = MobilePhone(c,s)
m2 = copy.copy(m1)
print(m1,m1.cpu,m1.screen)
print(m2,m2.cpu,m2.screen)
print("测试深拷贝。。。")
m3 = copy.deepcopy(m1)
print(m1,m1.cpu,m1.screen)
print(m3,m3.cpu,m3.screen)
结果:
测试浅拷贝。。。
<__main__.MobilePhone object at 0x000002EC6471EBA8> <__main__.Cpu object at 0x000002EC6471EAC8> <__main__.Screen object at 0x000002EC6471EB00>
<__main__.MobilePhone object at 0x000002EC64722278> <__main__.Cpu object at 0x000002EC6471EAC8> <__main__.Screen object at 0x000002EC6471EB00>
测试深拷贝。。。
<__main__.MobilePhone object at 0x000002EC6471EBA8> <__main__.Cpu object at 0x000002EC6471EAC8> <__main__.Screen object at 0x000002EC6471EB00>
<__main__.MobilePhone object at 0x000002EC64744208> <__main__.Cpu object at 0x000002EC647442B0> <__main__.Screen object at 0x000002EC64744320>
从结果中,发现浅拷贝中,MobilePhone对象发生变化,而里面的子对象cpu和screen均没有变化,深拷贝则都发生了变化。
他们都能够实现代码复用。
“is-a”关系,我们可以使用“继承”。从而实现子类拥有的父类的方法和属性。“is-a”关系指的是类似这样的关系:狗是动物,dog is animal。狗类就应该继承动物类。
“has-a”关系,我们可以使用“组合”,也能实现一个类拥有另一个类的方法和属性。”has-a”关系指的是这样的关系:手机拥有 CPU。 MobilePhone has a CPU。
'''
组合
'''
class MobilePhone:
def __init__(self,cpu,screen):
self.cpu = cpu
self.screen =screen
class Cpu:
def cpu_name(self):
print("我的型号是:高通的")
class Screen:
def show(self):
print("地有多圆,天有多方,我就可以展示多莫精彩!")
m = MobilePhone(Cpu(),Screen())
m.cpu.cpu_name()
m.screen.show()