다음 코드를 올바르게 실행 :인스턴스가 피클 링 될 Python 클래스를 꾸밀 수 있습니까?
import pickle
class MyClass():
def __init__(self, arg):
self.arg = arg
a = MyClass('my arg')
with open('/home/mahikeulbody/mypickle', 'wb') as file:
pickle.dump(a, file)
하지만 멀티 톤 클래스 얻을 수있는 장식 추가 :
import pickle
def multiton(cls):
instances = {}
def getinstance(arg):
if arg not in instances:
instances[arg] = cls(arg)
return instances[arg]
return getinstance
@multiton
class MyClass():
def __init__(self, arg):
self.arg = arg
a = MyClass('my arg')
with open('/home/michel/mypickle', 'wb') as file:
pickle.dump(a, file)
다음과 같은 오류 발생 :
pickle.dump(a, file)
_pickle.PicklingError: Can't pickle <class '__main__.MyClass'>: it's not the same object as __main__.MyClass
잘못 무엇입니까?
어,이 데코레이터에는 그 이상의 문제가 있습니다. 그것은 단지 클래스가 아니며 공장 기능이되었습니다. 예를 들어, 수표를 입력하거나 하위 클래스로 분류 할 수 없습니다. – delnan