How to copy a class instance in python?

前端 未结 3 1509
遥遥无期
遥遥无期 2021-02-07 03:16

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

3条回答
  •  长情又很酷
    2021-02-07 03:58

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

提交回复
热议问题