python-3.x - 如何使 OrderedSet 可腌制?
问题描述
集合的 python 文档链接到OrderedSet
数据类型的接收者。这个类的行为像一个集合,但保持插入顺序。
链接(在页面底部): https ://docs.python.org/3/library/collections.abc.html?highlight=orderedset
链接目标: https ://code.activestate.com/recipes/576694/
我现在想让这个类可腌制,但双向链表会导致递归错误。作为解决方案,我在此类中添加了以下方法:
def __getstate__(self):
""" Avoids max depth RecursionError when dumping with pickle"""
return list(self)
def __setstate__(self, state):
""" Tells pickle how to restore instance using state """
self.__init__(state)
这行得通,但我觉得在__init__
里面打电话很奇怪__setstate__
。此外,它需要从头开始重建链表。有没有更好的方法让这个类可以腌制?
解决方案
正如 Mad Physicist 在评论(如何使 OrderedSet pickleable?)中提到的那样,问题中提出的解决方案是合理的。为 OrderedSet 类定义以下方法为 pickle 提供了它需要存储的信息,然后重构 OrderedSet 的内容:
def __getstate__(self):
""" Avoids max depth RecursionError when dumping with pickle"""
return list(self)
def __setstate__(self, state):
""" Tells pickle how to restore instance using state """
self.__init__(state)
在内部,pickle 会将 的内容存储OrderedSet
为list
,然后可以通过使用存储的列表OrderedSet
调用 的__init__()
方法来重构 。OrderedSet
作为奖励,copy.deepcopy()
回退到腌制/取消腌制,copy.deepcopy()
现在也可以工作。
推荐阅读
- python - tensorflow Object_Detection 通过model_main.py训练,出现TypeError
- asp.net - 为什么我应该在 Web 配置中使用 customErrors 模式“关闭”?
- ios - 在 CollectionView 中解码时出现 JSON 解码器错误
- sql - 在 Eloquent 数据库 Laravel 中按最大值搜索
- openwrt - Openwrt:如何将bin文件打包成ipk包?
- java - 执行 maven 安装时的编译错误/问题
- javascript - 我可以打开一个未选择默认选项卡的新窗口(网页)吗
- elixir - 在 phoenix 中测试 web 组件时如何加载 repo?
- angular - LoadChildren 导航到特定路线 Angular 6
- python - Django 意外的 405 响应