试图在我的“变量”类中理解这个错误。
我希望在我的“Variable”类中存储sre.sre_模式。我刚开始复制Variable类,注意到它导致了我所有的Variable类实例的更改。我现在知道我需要deepcopy这个类,但是现在我遇到了“TypeError:cannotdeepcopythispatterobject”。当然,我可以将该模式存储为文本字符串,但我的其余代码已经需要编译的模式!用模式对象复制变量类的最佳方法是什么?
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
对类一无所知,也不知道如何复制它们。通过实现
__deepcopy__()
方法,您可以告诉deepcopy
如何复制对象:在Python version 3.7+中似乎已经修复了这个问题:
依据:https://docs.python.org/3/whatsnew/3.7.html#re
测试:
这可以通过修补3.7版python中的
copy
模块来解决:相关问题 更多 >
编程相关推荐