I have a custom class with a property that is a list of instances of a different custom class. I want to be able to efficiently generate a complete (i.e. deep) copy of it. I tried using the deepcopy method, but it is very slow. What is the most efficient way to do this? Is it true that the most pythonic way is to use deepcopy?
It would be perfect if someone could suggest a good way to have the class provide a method of copying an instance of itself and returning it. The below simple example is how I am doing it currently, with the do_baz function being outside the class.
import copy
class foo:
def __init__(self, bar):
self.bar = bar
def baz(self):
self.bar = self.bar[::-1]
def do_baz(foo_instance):
new_foo = copy.deepcopy(foo_instance)
new_foo.baz()
return new_foo
bar = [1,2,3]
foo_1 = foo(bar)
foo_2 = do_baz(foo_1)
foo_1.bar, foo_2.bar
Output:
([1, 2, 3], [3, 2, 1])
The closest question I could find to this was Most efficient and most Pythonic way to deep copy class instance and perform additional manipulation, but I did not see how to apply it here.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…