当前位置: 动力学知识库 > 问答 > 编程问答 >

python - 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)
分享给朋友:
您可能感兴趣的文章:
随机阅读: