Reputation: 519
A question about deepcopy in Python:
I have a class A which contains a list of objects from class B, and a class C which contains a list of objects from class 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
So I want C to have a Split function which, given an A object a
and a B object b
in a.S
, will make two new A objects: one containing the 'buddies' of b
(which are in a.S
), one containing of the rest of a.S
.
The problem is, I don't know how to figure out what the designated b becomes in the deepcopy. In other words,
how do I find
new_b
in the above code?
(Note: In my actual code it is important to do it in this order, i.e. adding new_a
and then splitting a
into left
and right
would not work.)
Upvotes: 1
Views: 236
Reputation: 2845
This code should do what you were looking for.
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
Upvotes: 0
Reputation: 28390
The answer is that the designated b does not become anything other than b in deep copy as you are not deep copying b at all. So just replace new_b
with b
in your example.
Upvotes: 1