下面的代码运行正常:是否可以修饰其实例将被酸洗的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