Home > Blockchain >  How to copy a class object in python
How to copy a class object in python

Time:05-13

This is quite a simple question, however I cannot seem to figure out how to do it. I simply need to make a copy of a class object, for example:

class Foo():
     def __init__(self, nums):
          self.nums = nums

A = Foo(5)

I tried to do both A.copy() and A.deepcopy(), but I get "'Foo' object has no attribute 'copy'" This may be a super simple fix, however I have never used the copy module before and am not aware of why this may be an issue. For reference, I need the copied object to be mutable (without affecting the original) so I figured the best way would be to use .deepcopy().

CodePudding user response:

You're right, using deepcopy from the built-in copy module is the way to go, since you want the exact replica of the Object Foo.

from copy import deepcopy

class Foo:
    ...

Foo_copy = deepcopy(Foo)
# Foo_copy(5) will work exactly the same way Foo(5) would work without affecting it.
# Foo_copy = deepcopy(Foo(5)) works the same way as well, but here, Foo_copy.nums will be 5.

Here, passing the object Foo(5) will return a Foo object, passing it without any args will return __name__.Foo

  • Related