使用deepcopy创建一个新的obj但是新的obj子类仍然与旧的obj共享变量

时间:2014-03-21 15:38:46

标签: python deep-copy

我正在创建一个对象列表,当我创建新实例时,第三级别的所有属性的内容与上一次分配相同。即使我使用deepcopy,外部类也是副本,但内部类不是。

例如:

PCC->  {'id': 'PCC1'}
    PA->  {'id': 'PA1', 'o': 'O1'}
        PC->  {'id': 'PC1'}
            PT
            ->P  p2
            ->V  v2
            ->R  r2
        PC->  {'id': 'PC2'}
            PT
            ->P  p2
            ->V  v2
            ->R  r2

以下是我的代码示例:

import copy

class V:
    id = ''
class P:
    id = ''    
class R:
    id = ''
class PT:    
    v = V()
    p = P()
    r = R()
    def __copy__(self):
        print ("COPY!!!") #define explicit copy behaviour
        s = self.__class__()
        s.p = self.p.id = '' # make a copy of the list rather than a pointer to same
        s.v = self.v.id = '' # make a copy of the list rather than a pointer to same
        s.r = self.r.id = '' # make a copy of the list rather than a pointer to same
        return s

class C:
    id = ''
class PC(C):
    pr = PT()
class O:
    name = ''
class A:
    id = ''
    o = O()
class PA(A):
    pc = []#PC
class CC:
    id = ''
class PCC(CC):
    pa = PA()

if __name__ == '__main__':
    pcc = PCC()
    pcc.id = 'PCC1'
    pcc.pa.id = 'PA1'
    pcc.pa.o = 'O1'

    pc = PC()
    pc.id = 'PC1'
    pc.pr.p.id = 'p1'
    pc.pr.v.id = 'v1'
    pc.pr.r.id = 'r1'

    pcc.pa.pc.append(copy.deepcopy(pc))

    pc.id = 'PC2'
    pc.pr.p.id = 'p2'
    pc.pr.v.id = 'v2'
    pc.pr.r.id = 'r2'

    pcc.pa.pc.append(copy.deepcopy(pc))    

    print('PCC-> ' , vars(pcc))
    print('\t PA-> ' , vars(pcc.pa))

    #print(pcc.has_producer_agreement.clauseAlgorithme)
    x = PC()
    for x in pcc.pa.pc:
        print('\t\t PC-> ' , vars(x))
        print('\t\t\t PT')
        print('\t\t\t ->P ' , x.pr.p.id)
        print('\t\t\t ->V ' , x.pr.v.id)
        print('\t\t\t ->R ' , x.pr.r.id)

1 个答案:

答案 0 :(得分:1)

您正在使用类属性,这些属性始终在实例之间共享。 copy.deepcopy()只会复制实例属性。

使用__init__方法来创建实例属性:

class PT:    
    def __init__(self):
        self.v = V()
        self.p = P()
        self.r = R()

class PC(C):
    def __init__(self):
        self.pr = PT()

class A:
    id = ''

    def __init__(self):
        self.o = O()

class PA(A):
    def __init__(self):
        self.pc = []

class PCC(CC):
    def __init__(self):
        self.pa = PA()