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