Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implementing "copy constructor" vs. using copy()

Tags:

python

What is generally preferred, in terms of python conventions + speed? something like:

class Object(object):
    def __init__(self, other_object=None):
        if other_object:
            self.value = other_object.value
        else:
            self.value = something

and then

obj = Object(other_object)

or, using copy():

from copy import copy
obj = copy(other_object)
like image 773
AAlon Avatar asked Oct 16 '25 14:10

AAlon


1 Answers

The things are very simple, considering the documentation of the copy module:

In order for a class to define its own copy implementation, it can define special methods __copy__() and __deepcopy__(). The former is called to implement the shallow copy operation; no additional arguments are passed. The latter is called to implement the deep copy operation; it is passed one argument, the memo dictionary. If the __deepcopy__() implementation needs to make a deep copy of a component, it should call the deepcopy() function with the component as first argument and the memo dictionary as second argument.

So, if you feel that the standard copy() or deepcopy() works slow or has some other issues, just implement one of the methods mentioned above. That way you are sticking to the well-known Python objects copying mechanism, still copying the object the way you want it to be copied.

like image 166
Zaur Nasibov Avatar answered Oct 18 '25 03:10

Zaur Nasibov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!