Python:类对象的赋值、深拷贝、浅拷贝

赋值操作

只是形成两个变量,实际上还是指向同一个对象,变量存储的是对象的引用。

class CPU:
    pass
        

# 变量的赋值
cpu1 = CPU()
cpu2 = cpu1
print(cpu1)  # <__main__.CPU object at 0x0000017B21356460>
print(cpu2)  # <__main__.CPU object at 0x0000017B21356460>

浅拷贝

Python拷贝一般都是浅拷贝,拷贝时,对象包括的子对象内容不拷贝,因此,源对象与拷贝对象会引用同一个子对象。(只拷贝主对象,子对象还是引用同一个。)

import copy as cp


class CPU:
    pass


class Disk:
    pass


class Computer:
    def __init__(self, cpu, disk):
        self.cpu = cpu
        self.disk = disk


# 类对象的浅拷贝
cpu1 = CPU()
disk = Disk()
computer = Computer(cpu1, disk)
computer2 = cp.copy(computer)

print(computer, computer.cpu, computer.disk)
# <__main__.Computer object at 0x000002365C8ACBB0> <__main__.CPU object at 0x000002365C8ACD90> <__main__.Disk object at 0x000002365C8AC430>
print(computer2, computer2.cpu, computer2.disk)
# <__main__.Computer object at 0x000002365C9D65E0> <__main__.CPU object at 0x000002365C8ACD90> <__main__.Disk object at 0x000002365C8AC430>

深拷贝

使用copy模块的deepcopy函数,递归拷贝对象及其中包括的子对象,源对象和拷贝对象以及所有子对象都不相同。

import copy


class CPU:
    pass


class Disk:
    pass


class Computer:
    def __init__(self, cpu, disk):
        self.cpu = cpu
        self.disk = disk


# 类对象的深拷贝
cpu1 = CPU()
disk = Disk()
computer = Computer(cpu1, disk)
computer3 = copy.deepcopy(computer)

print(computer, computer.cpu, computer.disk)
# <__main__.Computer object at 0x000002365C8ACBB0> <__main__.CPU object at 0x000002365C8ACD90> <__main__.Disk object at 0x000002365C8AC430>
print(computer3, computer3.cpu, computer3.disk)
# <__main__.Computer object at 0x00000180BA7E3340> <__main__.CPU object at 0x00000180BA7FB100> <__main__.Disk object at 0x00000180BA7FB130>

你可能感兴趣的:(python)