下面的代碼運行正常:是否可以修飾其實例將被酸洗的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