【发布时间】:2013-01-24 17:23:55
【问题描述】:
以下代码运行正确:
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)
但是添加一个装饰器来获得一个 multiton 类:
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
怎么了?
【问题讨论】:
-
呃,这个装饰器的问题不止于此。它只是不是一个类,它已成为一个工厂函数。例如,您不能使用它键入检查或子类化它。
标签: python decorator pickle python-decorators