在Python中使用deepcopy引用子对象的位置

时间:2013-08-02 03:57:43

标签: python deep-copy

关于Python中深度复制的问题:

我有一个包含B类对象列表的A类,以及一个包含A类对象列表的C类。

class A(object):
    def __init__(S):
        self.S = set(S)

class B(object):
    def __init__(buddies):
        self.buddies = set(buddies)

class C(object):
    def __init__(L):
        self.L = set(L)
    def SplitA(a,b):
        left = deepcopy(a)
        left.S -= new_b.buddies
        right = A(new_b.buddies)
        L |= left
        L |= right

所以我希望C有一个Split函数,在a中给定一个A对象b和一个B对象a.S,它将生成两个新的A对象:一个包含'伙伴b(位于a.S中),其中一个包含其余a.S

问题是,我不知道如何弄清楚指定的b在深度镜中的含义。换句话说,

  

如何在上面的代码中找到new_b

(注意:在我的实际代码中,按此顺序执行此操作非常重要,即添加new_a,然后将a拆分为leftright将无效。)

2 个答案:

答案 0 :(得分:1)

答案是指定的b在深拷贝中不会变成b以外的任何东西,因为你根本不是深拷贝b。因此,只需在示例中将new_b替换为b

答案 1 :(得分:0)

此代码应该可以满足您的需求。

from copy import deepcopy


class A(object):
    def __init__(self, S):
        self.S = set(S)


class B(object):
    def __init__(self, buddies):
        self.buddies = set(buddies)


class C(object):
    def __init__(self, L):
        self.L = set(L)

    def SplitA(self, a, b):
        left = set()
        left -= b.buddies   # Since the objects in the sets are unchanged
                            # you can do a set difference that will leave you
                            # with only the members of a that are not in b
        left = deepcopy(left)  # Now get a deep copy of left
        right = deepcopy(b.S)  # and a deep copy of b.S
        self.L |= left      # and combine them
        self.L |= right