I saw similar question here on stackoverflow but it wasn’t satisfactorily answered.
(link to this question – How to copy a python class? )
So my question is, is there any possible way to create a copy of class (instance of a class), that is stored in variable A and assign this copy of class to new variable B without having these variables A and B mutually dependent?
To be clear – is there a quite simple way?
Model situation would be:
class B:
def __init__(self, li):
self.l = li * 5
self.u = 5
class A:
def __init__(self):
self.x = [1, 2, 3]
self.c = B([45, 1, 3])
self.i = 1
x = A()
y = x #This copies only reference to x
Implement
__copy__()for your class, then you can usecopy.copy()to create a copy of the instance. This can’t be done automatically due to the nature of Python objects (there is no way of knowing what variables will be set on an instance, and no way of knowing how it’s been mutated, it’s up to you to ensure that data is copied correctly).Normally, presuming a class that functions in a normal way,
__copy__()will probably be something simple like this for a supposed classSomeClass:Naturally, exact implementation will vary wildly based on the class itself.