对象的浅拷贝和深拷贝
浅拷贝:
python 中一般都是浅拷贝,拷贝时对象包含的子对象内容不拷贝,因此 源对象和拷贝对象会引用用一个子对象
深拷贝:
使用copy 模块的deepcopy函数,递归拷贝对象中包含的子对象,源对象和拷贝对象的所有子对象也不同
import copy
class MobilePhone:
def __init__(self, cpu, screen):
self.cpu = cpu
self.screen = screen
class CPU:
def calculate(self):
print("calculate 12345")
print("cpu is ", self)
class Screen:
def show(self):
print("show 12345")
print("show is ", self)
c1 = CPU()
# 赋值, m2 和m1 一样
c2 = c1
print(c1)
print(c2)
#返回值:
# <__main__.CPU object at 0x000001409C8AB040>
#<__main__.CPU object at 0x000001409C8AB040>
#指向地址一致
# 浅拷贝
s1 = Screen()
m1 = MobilePhone(c1, s1)
m2 = copy.copy(m1)
print(m1, m1.cpu, m1.screen)
print(m2, m2.cpu, m2.screen)
#返回值:
#<__main__.MobilePhone object at 0x000001409C8AB0A0> <__main__.CPU object at 0x000001409C8AB040> <__main__.Screen object at 0x000001409C8AB070>
#<__main__.MobilePhone object at 0x000001409C8ABDF0> <__main__.CPU object at 0x000001409C8AB040> <__main__.Screen object at 0x000001409C8AB070>
#子对象地址一致,子对象指向地址一致,未被复制
#深拷贝
m3 = copy.deepcopy(m1)
print(m1, m1.cpu, m1.screen)
print(m3, m3.cpu, m3.screen)
#返回值:
#<__main__.MobilePhone object at 0x000001409C8AB0A0> <__main__.CPU object at 0x000001409C8AB040> <__main__.Screen object at 0x000001409C8AB070>
#<__main__.MobilePhone object at 0x000001409C8ABC70> <__main__.CPU object at 0x000001409C8ABBB0> <__main__.Screen object at 0x000001409C8ABB50>
#所有对象均被复制
组合
组合:has-a 关系:手机拥有CPU
继承:is-a 关系:狗是一个动物
class A:
def say(self):
print("AAA")
class B:
def __init__(self, a):
self.a = a
a = A()
b = B(a)
b.a.say()