python中deepcopy函数_python – copy.deepcopy使用自定义的__new __()方法在对象上引发TypeError...
我想實現(xiàn)一個符號類型,它跟蹤我們已經(jīng)擁有的符號(保存在_sym_table中),如果它們存在則返回它們,否則創(chuàng)建新符號.代碼:
# -*- 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__()
但是當(dāng)我在這樣的Symbol實例列表上調(diào)用copy.deepcopy時,會引發(fā)異常:
a = Symbol('a')
b = Symbol('b')
s = [a, b]
t = copy.deepcopy(s)
錯誤消息:
Traceback (most recent call last):
File "xxx.py", line 7, in
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__方法對這些對象進行深層復(fù)制?
>以及關(guān)于何時以及如何使用copy.deepcopy的任何建議?
非常感謝!
總結(jié)
以上是生活随笔為你收集整理的python中deepcopy函数_python – copy.deepcopy使用自定义的__new __()方法在对象上引发TypeError...的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 安卓手机如何设置dns 如何通过手机更改
- 下一篇: 系统改变号(SCN)详解