Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
3.7k views
in Technique[技术] by (71.8m points)

python - Efficient way to create copy of custom class

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can simply add a copy() method to your class and return deepcopy(self):

import copy

class foo:
    def __init__(self, bar):
        self.bar = bar

    def baz(self):
        self.bar = self.bar[::-1]

    def copy(self):
        return copy.deepcopy(self)

bar = [1, 2, 3]
foo_1 = foo(bar)
foo_2 = foo_1.copy()
foo_2.baz()
print(foo_1.bar)
print(foo_2.bar)

Output:

[1, 2, 3]
[3, 2, 1]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...