이미있는 심볼을 추적하고 (_sym_table
에 저장되어있는) 심볼 유형을 구현하고이를 반환하거나 새로운 것들. 코드 : 나는 그런 Symbol
인스턴스 목록에 copy.deepcopy
를 호출 할 때, 예외가 발생copy.deepcopy는 자체 정의 된 __new __() 메서드를 사용하여 객체에 TypeError를 발생시킵니다.
# -*- 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__()
:
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)
그래서 제 질문은 다음과 같습니다
- H 내가 정의한
__new__
메소드를 사용하여이 오브젝트들에 깊은 복사를 할 수 있습니까? copy.deepcopy
을 언제 어떻게 사용할 수 있습니까?
감사합니다.