TypeError:无法深度复制此模式对象 [英] TypeError: cannot deepcopy this pattern object
问题描述
试图了解我的变量类中的此错误。
Trying to understand this error in my "Variable" class.
我希望在我的变量类中存储一个sre.SRE_Pattern。我刚刚开始复制Variable类,并注意到这导致我的所有Variable类实例都发生了更改。我现在知道需要深度复制此类,但是现在遇到 TypeError:无法深度复制此模式对象。当然,我可以将模式存储为文本字符串,但是我的其余代码已经期望使用已编译模式!用模式对象复制Variable类的最佳方法是什么?
I was hoping to store a sre.SRE_Pattern in my "Variable" class. I just started copying the Variable class and noticed that it was causing all my Variable class instances to change. I now understand that I need to deepcopy this class, but now I run into "TypeError: cannot deepcopy this pattern object". Sure, I can store the pattern as a text string but the rest of my code already expects a compiled pattern! What would be the best way to copy my Variable class with a pattern object?
import re
from copy import deepcopy
class VariableWithRE(object):
"general variable class"
def __init__(self,name,regexTarget,type):
self.name = name
self.regexTarget = re.compile(regexTarget, re.U|re.M)
self.type = type
class VariableWithoutRE(object):
"general variable class"
def __init__(self,name,regexTarget,type):
self.name = name
self.regexTarget = regexTarget
self.type = type
if __name__ == "__main__":
myVariable = VariableWithoutRE("myName","myRegexSearch","myType")
myVariableCopy = deepcopy(myVariable)
myVariable = VariableWithRE("myName","myRegexSearch","myType")
myVariableCopy = deepcopy(myVariable)
推荐答案
deepcopy
不了解您的课程,也不知道如何应对y他们。
deepcopy
doesn't know anything about your classes and doesn't know how to copy them.
您可以通过实现 __ deepcopy__告诉
方法: deepcopy
如何复制对象。 ()
You can tell deepcopy
how to copy your objects by implementing a __deepcopy__()
method:
class VariableWithoutRE(object):
# ...
def __deepcopy__(self):
return VariableWithoutRE(self.name, self.regexTarget, self.type)
这篇关于TypeError:无法深度复制此模式对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!