gpt4 book ai didi

python - 是否可以修饰一个实例将被 pickle 的 Python 类?

转载 作者:行者123 更新时间:2023-12-01 05:50:29 24 4
gpt4 key购买 nike

以下代码运行正确:

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

出了什么问题?

最佳答案

Pickle 必须能够直接加载该类。您的装饰器用工厂函数替换了该类,从而使 pickle 无法导入该类本身。

使用单独的工厂函数,而不是装饰器,返回“私有(private)”类(但仍然可以直接导入):

class _MyClass():   
def __init__(self, arg):
self.arg = arg

def MyClass(arg, instances={}):
if arg not in instances:
instances[arg] = _MyClass(arg)
return instances[arg]

关于python - 是否可以修饰一个实例将被 pickle 的 Python 类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14507112/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com