Python-如何使这个无法点刺的对象可以被点刺? [英] Python - How can I make this un-pickleable object pickleable?

查看:84
本文介绍了Python-如何使这个无法点刺的对象可以被点刺?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,我有一个对象,其中包含很多不可刺的东西(pygame事件,orderDicts,时钟等),我需要将其保存到磁盘.

就是,如果我能得到这个东西来存储一个具有进度的字符串(我只需要一个整数),那么我就可以将其传递给对象的init,它将重建所有这些东西.不幸的是,尽管我可以将其保存为单个整数,但无法更改它,但我正在使用的(Renpy) 框架会腌制该对象并尝试加载该对象.

所以,我要问的是,我该如何覆盖方法,以便每当pickle尝试保存对象时,它仅保存进度值,并且每当尝试加载对象时,它都会从中创建一个新实例.进度值?

我已经看过__repr__方法,但是我不确定在我的情况下如何使用它.

解决方案

您要查找的钩子是 解决方案

The hook you're looking for is __reduce__. It should return a (callable, args) tuple; the callable and args will be serialized, and on deserialization, the object will be recreated through callable(*args). If your class's constructor takes an int, you can implement __reduce__ as

class ComplicatedThing(object):
    def __reduce__(self):
        return (ComplicatedThing, (self.progress_int,))

There are a few optional extra things you can put into the tuple, mostly useful for when your object graph has cyclic dependencies, but you shouldn't need them here.

这篇关于Python-如何使这个无法点刺的对象可以被点刺?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆