【发布时间】:2011-09-10 21:07:43
【问题描述】:
试图在我的“变量”类中理解这个错误。
我希望在我的“变量”类中存储一个 sre.SRE_Pattern。我刚开始复制变量类,并注意到它导致我所有的变量类实例都发生了变化。我现在明白我需要对这个类进行深度复制,但现在我遇到了“TypeError:无法深度复制这个模式对象”。当然,我可以将模式存储为文本字符串,但我的其余代码已经期望编译模式!用模式对象复制我的变量类的最佳方法是什么?
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()如何处理特定类型(但请注意,如果需要,您可以向内置类型添加属性)。 -
代码中的哪一行抛出异常?我已经复制了它然后编译->它在我身边没有任何错误。我发现的唯一一件事是你尝试使用重写 python 方法'type'的变量,这不是很好的风格。
-
最后一行在 Python 2.6 中为我抛出了错误。