简体   繁体   中英

Create a new class object that's identical to an existing one but does not refer to it

def _replace(self, **kargs):
    for item in kargs.items():
        if item[0] not in self._fields:
            raise TypeError
    if self._mutable:
        for item in kargs.items():
            self.__dict__[item[0]] = item[1]

    else:
        new_self = self
        for item in kargs.items():
            new_self.__dict__[item[0]] = item[1]
        return new_self

I am working with a class where one if its arguments is mutable which is either True or False to determine if the class willl be mutable. This is saved under self._mutable . So as you can see in this code, I tried to make a completely seperate copy of the class but it still refers to the old one when I try to call this _replace method.

You can use deepcopy

import copy
new_obj = copy.deepcopy(obj)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM