I am trying to copy instances of a custom class in Python 3.3, similar to how dict.copy()
and list.copy()
work. How do I go about this?
Here is an example of my custom class:
class CustomClass(object): # Custom class example
def __init__(self, thing):
self.thing = thing
Yes, you can use copy. deepcopy . so just c2 = copy.
To get a fully independent copy of an object you can use the copy. deepcopy() function.
The copy() returns a shallow copy of the list, and deepcopy() returns a deep copy of the list. As you can see that both have the same value but have different IDs.
Copy an Object in Python In Python, we use = operator to create a copy of an object. You may think that this creates a new object; it doesn't. It only creates a new variable that shares the reference of the original object.
In general, you can use the copy
module to produce copies of Python objects.
copy.copy()
will produce a shallow copy; a new instance is created but all attributes are simply copied over. If any of your attributes are mutable and you mutate those objects you'll see those changes reflected on both objects.
copy.deepcopy()
will produce a copy recursively; any mutable objects will themselves be cloned.
If your class implements a __copy__
method it'll be used to create a shallow copy of the object; return a new instance with attributes copied over and altered as needed.
Similarly, you can implement a __deepcopy__
method to implement a custom deep copy method; it'll be passed the memo
state, pass this on to recursive copy.deepcopy()
calls.
Note that you cannot use this to copy a class object however. Classes are meant to be singletons; you don't need to create a copy in that case. You can use subclassing instead, or a class factory function, to produce distinct class objects.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With