在没有命名引用的情况下使用 Pickle

发布于 2025-01-12 14:48:19 字数 639 浏览 2 评论 0原文

我正在尝试腌制一些自定义类,而不参考原始类本身。

我尝试修改原始的 getstate() 函数以仅返回字典。这个解决方案看起来很有效,因为它只返回一个字典对象,但是当我尝试恢复它时,它仍然需要原始类。

这就是我为获取对象的字典所做的事情:

def __getstate__(self):
    odict = self.__dict__.copy()
    return odict

这是我的保存代码:

utils.save_pickle(self.__getstate__(), self.save_path)

其中 save_pickle 只是:

def save_pickle(obj,name):
    with open(name, 'wb') as handle:
        pickle.dump(obj, handle, protocol=2)
    return

但是,当我尝试取消数据时,pickle 仍然知道这是一个自定义类并使用 setstate() 函数。我怎样才能实现只腌制一本字典而不是对类的引用。

I am trying to pickle some of my custom classes without any reference to the original class itself.

I tried to modify the original getstate() function to just return a dictionary. This solution looks like it works, because its just returns a dictionary object, however when I tried to recover it still requires the original class.

This is what I do for getting the object's dictionary:

def __getstate__(self):
    odict = self.__dict__.copy()
    return odict

And this is my saving code:

utils.save_pickle(self.__getstate__(), self.save_path)

where save_pickle is just:

def save_pickle(obj,name):
    with open(name, 'wb') as handle:
        pickle.dump(obj, handle, protocol=2)
    return

However when I tried to unpickle the data, pickle still knows that this is a custom class and uses the setstate() function of that class. How can I achieve just to pickle a dictionary and not a reference to class.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

┈┾☆殇 2025-01-19 14:48:19

不确定我是否正确回答了你的问题。但你总是可以认为类是指令:

import pickle


class Desk:
    def __init__(self, name):
        self.name = name
        self.length = 10
        self.width = 20


desk = Desk("old")

pickled_dict = pickle.dumps(desk.__dict__)
desk= None

# Reassemble
cls_dict = pickle.loads(pickled_dict)
desk = Desk("new")
desk.__dict__.update(cls_dict)
assert desk.name == "old"

Not sure if i got your question right. But you always can think classes are dicts:

import pickle


class Desk:
    def __init__(self, name):
        self.name = name
        self.length = 10
        self.width = 20


desk = Desk("old")

pickled_dict = pickle.dumps(desk.__dict__)
desk= None

# Reassemble
cls_dict = pickle.loads(pickled_dict)
desk = Desk("new")
desk.__dict__.update(cls_dict)
assert desk.name == "old"
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文