Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to copy instances of a custom defined class in Python 3.3?

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
like image 755
ASCIIThenANSI Avatar asked Apr 01 '15 18:04

ASCIIThenANSI


People also ask

Can you copy an instance of a class in Python?

Yes, you can use copy. deepcopy . so just c2 = copy.

How do I return a copy of a class object in Python?

To get a fully independent copy of an object you can use the copy. deepcopy() function.

What is the difference between copy copy () and copy Deepcopy ()?

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.

How can you copy items in Python?

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.


1 Answers

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.

like image 143
Martijn Pieters Avatar answered Oct 11 '22 15:10

Martijn Pieters