Custom class instance copying
I'm new to programming and Python. The problem I 开发者_如何学编程have is with removing list elements that are instances of custom class.
import copy
class some_class:
pass
x = some_class()
x.attr1 = 5
y = some_class()
y.attr1 = 5
z = [x,y]
zcopy = copy.deepcopy(z)
z.remove(zcopy[0])
This returns: ValueError: list.remove(x): x not in list
Is there a simple way to remove element from list by using reference from deepcopied list?
edit: Thanks for your answers. I found some solution using indexing. It's not pretty but it does the job:
import copy
class some_class:
pass
x = some_class()
x.attr1 = 5
y = some_class()
y.attr1 = 5
z = [x,y]
zcopy = copy.deepcopy(z)
del z[zcopy.index(zcopy[0])]
No, because the call to deepcopy
creates a copy of the some_class
instance. That copy, zcopy[0]
is a different object from the original, z[0]
, so when you try to remove zcopy[0]
from the list z
, it rightly complains that the copy doesn't exist in the original list. Furthermore, there is no link between the copied object and the original object, which is the intent of deepcopy
.
I suppose you could implement a __deepcopy__
method in your class, which returns a copy that maintains some reference to the original object. Then you could use that reference to get the original object, z[0]
, from the copy, zcopy[0]
. It strikes me as a rather odd thing to do, though, and probably not a good idea. Without further information, I'd suggest just using copy.copy
instead of copy.deepcopy
.
精彩评论