2

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

4
  • 2
    copy.deepcopy(A)? Commented May 12, 2022 at 17:37
  • 2
    Just refer to the documentation... Commented May 12, 2022 at 17:37
  • @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! Commented May 12, 2022 at 17:40
  • 1
    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 Commented May 12, 2022 at 18:17

1 Answer 1

4

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

Sign up to request clarification or add additional context in comments.

1 Comment

well, actually, here you don't need copy.deepcopy

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.