I would like to make a copy of a class instance in python. I tried copy.deepcopy
but I get the error message:
RuntimeError: Only Variables cr
One way to do that is by implementing __copy__
in the C
Class like so:
class A:
def __init__(self):
self.var1 = 1
self.var2 = 2
self.var3 = 3
class C(A):
def __init__(self, a=None, b=None, **kwargs):
super().__init__()
self.a = a
self.b = b
for x, v in kwargs.items():
setattr(self, x, v)
def __copy__(self):
self.normalizeArgs()
return C(self.a, self.b, kwargs=self.kwargs)
# THIS IS AN ADDITIONAL GATE-KEEPING METHOD TO ENSURE
# THAT EVEN WHEN PROPERTIES ARE DELETED, CLONED OBJECTS
# STILL GETS DEFAULT VALUES (NONE, IN THIS CASE)
def normalizeArgs(self):
if not hasattr(self, "a"):
self.a = None
if not hasattr(self, "b"):
self.b = None
if not hasattr(self, "kwargs"):
self.kwargs = {}
cMain = C(a=4, b=5, kwargs={'r':2})
del cMain.b
cClone = cMain.__copy__()
cMain.a = 11
del cClone.b
cClone2 = cClone.__copy__()
print(vars(cMain))
print(vars(cClone))
print(vars(cClone2))