简体   繁体   English

创建一个与现有对象相同但未引用它的新类对象

[英]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. 我正在使用一个类,如果它的参数是可变的,则该类为True或False,以确定该类是否可变。 This is saved under self._mutable . 这保存在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. 因此,如您在这段代码中所看到的,我试图制作一个完全独立的类副本,但是当我尝试调用此_replace方法时,它仍然引用旧的类。

You can use deepcopy 您可以使用Deepcopy

import copy
new_obj = copy.deepcopy(obj)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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