我想实现一个符号类型,它跟踪我们已经拥有的符号(保存在 中_sym_table
),如果它们存在则返回它们,否则创建新的。编码:
# -*- coding: utf-8 -*-
_sym_table = {}
class Symbol(object):
def __new__(cls, sym):
if sym not in _sym_table:
return super().__new__(cls)
else:
return _sym_table[sym]
def __init__(self, sym):
self.sym = sym
_sym_table[sym] = self
def __str__(self):
return self.sym
def __cmp__(self, other):
return self is other
def __hash__(self):
return self.sym.__hash__()
但是,当我调用copy.deepcopy
此类Symbol
实例的列表时,会引发异常:
a = Symbol('a')
b = Symbol('b')
s = [a, b]
t = copy.deepcopy(s)
错误信息:
Traceback (most recent call last):
File "xxx.py", line 7, in <module>
t = copy.deepcopy(s)
File "/usr/lib/python3.2/copy.py", line 147, in deepcopy
y = copier(x, memo)
File "/usr/lib/python3.2/copy.py", line 209, in _deepcopy_list
y.append(deepcopy(a, memo))
File "/usr/lib/python3.2/copy.py", line 174, in deepcopy
y = _reconstruct(x, rv, 1, memo)
File "/usr/lib/python3.2/copy.py", line 285, in _reconstruct
y = callable(*args)
File "/usr/lib/python3.2/copyreg.py", line 88, in __newobj__
return cls.__new__(cls, *args)
TypeError: __new__() takes exactly 2 arguments (1 given)
所以我的问题是:
- 如何使用自定义
__new__
方法对这些对象进行深度复制? - 以及关于何时以及如何使用的任何建议
copy.deepcopy
?
非常感谢!