0
votes

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().

1
copy.deepcopy(A)? - Barmar
Just refer to the documentation... - Random Davis
@Barmar Shoot! I see, I have used the module in the earlier stages of the code and thought it was only an attribute to put at the end.. such as A.copy()... my bad! Thanks! - ReDedrik
You can, of course, write your own function to manually copy your object. A shallow copy of a straight-forward object like yours could be defined simply as def copy(self): return Foo(**vars(self)). If initialization would affect the incoming arguments, something like instance = object.__new__(Foo); vars(instance).update(vars(self)); return instance could work - juanpa.arrivillaga

1 Answers

1
votes

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