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

2024-10-03 15:27:16 发布

您现在位置:Python中文网/ 问答频道 /正文

关于Python中的deepcopy的一个问题:

我有一个类a,它包含一个类B中的对象列表,还有一个类C,它包含一个类a中的对象列表

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对象ba.S,它将生成两个新的a对象:一个包含b(在a.S)的‘伙伴’,一个包含a.S的其余部分。你知道吗

问题是,我不知道如何找出指定的b在deepcopy中变成了什么。换句话说

how do I find new_b in the above code?

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


Tags: 对象selfright列表newobjectinitdef
2条回答

这段代码应该符合你的要求。你知道吗

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

答案是指定的b在深度复制中不会变成除b以外的任何东西,因为您根本不是深度复制b。所以在您的示例中,只需将new_b替换为b。你知道吗

相关问题 更多 >