python - 将对象解压成 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
解决方案
推荐阅读
- visual-studio-code - 如何在vs代码工作区中自动收缩多根文件夹
- azure-synapse - 写入增量接收器时对数据进行分区
- javascript - 在我的终端节点(文件名)命令不起作用它没有显示如何修复它?
- python - 使用 Pika 使用 RabbitMq 并使用 Socket.io 推送
- python-3.x - 在 Jupiter Notebook 中用 ipywidget 链接两个数字
- android - 如何在 Uri 中设置图像
- mongodb - 将对象附加到嵌套对象内的数组中
- r - 如何按 R 中的区域对 DF 内的 ID 求和?
- android - curl:(60)SSL证书问题:证书链中的自签名证书更多详细信息:https://curl.se/docs/sslcerts.html
- python - 如何在 Pandas 中执行虚拟函数以及聚合其他列的总和?