集合的 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__。此外,它需要从头开始重建链表。有没有更好的方法让这个类可以腌制?