首页 > 解决方案 > 将对象解压成 int

问题描述

当它被解开时,我需要将一个对象更改为一个 int。我正在创建一个 unpickler 并覆盖 find_global,当我可以 unpickle 为任意类型时它可以工作。int从返回find_global不起作用,因为 unpickler 试图填充它__dict__,我得到AttributeError: 'int' object has no attribute '__dict__'. 当 unpickler 解开这个对象时,它会__init__使用我想要的 int 值set_state和空状态调用。

我需要这样做,因为该对象来自第三方库,我们不再使用该库。

def find_global(modulename, classname):
    if modulename == 'some.module' and classname == 'ClassThatNeedsToBeAnInt':
        # I need to get the unpickler to unpickle this into a int

unpickler.find_global = find_global

我试过用一个__new__方法创建一个类,但即使我返回一个 int,unpickler 也会继续调用int.set_state

我有这个部分解决方案,但我想要一个实际的 int。

class SubclassedInt(int):
    def __setstate__(self, state):
        pass


def find_global(modulename, classname):
    if modulename == 'some.module' and classname == 'ClassThatNeedsToBeAnInt':
        return SubclassedInt

unpickler.find_global = find_global

标签: pythonpython-3.xpickle

解决方案


推荐阅读