python学习(8)-对象拷贝、组合

对象的浅拷贝和深拷贝

浅拷贝:
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()
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值