Python 3.x python:pickle can';t存储本地函数(Can';t pickle local object)

Python 3.x python:pickle can';t存储本地函数(Can';t pickle local object),python-3.x,class,dictionary,Python 3.x,Class,Dictionary,在我的类方法中,我使用count生成唯一ID,我希望将其存储在类中: from collections import Counter, defaultdict import pickle class A: def __init__(self): self.models = {} def func1(self, data, names): ll = [] for n, seq_list in enumerate(data):

在我的类方法中,我使用
count
生成唯一ID,我希望将其存储在类中:

from collections import Counter, defaultdict
import pickle

class A:
   def __init__(self):
      self.models = {}

   def func1(self, data, names):
      ll = []
      for n, seq_list in enumerate(data):
          __counter = count(start=0)

          def _genid():
             return next(__counter)

          __ids = defaultdict(_genid)

          # Here we process seq_list and fill __ids
          # ...

          self.models[name] = [None, None, None, __ids]

   def save_models(self, obj, filename="models.bin"):
        try:
            with open(filename, 'wb') as f:
                pickle.dump(obj, f)
        except IOError as e:
            raise Exception("Failed to open file for writing: %s" % e)

...

data = [['A', 'BB', 'B', 'B', 'B'],
        [['C', 'D', 'E', 'B'], ['E', 'B'], ['C', 'D', 'E', 'B', 'B', 'F']],
        ['A', 'G'],
        [['AA', 'C', 'B', 'B'], ['F', 'D'], ['BB', 'E', 'E', 'F', 'B', 'A']]]
names = ['name1', 'name2', 'name3', 'name4'    

aclass = A()
aclass.func1(data, names)
aclass.save_models(aclass)
此时
save_models()
生成错误:AttributeError:无法pickle本地对象“A.func1..\u genid”

所以我有两个问题: -有没有办法让
pickle
保存我的课程?
-如果没有,是否有更简单的方法在类中存储
ID
并能够对其进行pickle?

选项1:避免
\u genid
并使用简单的整数变量进行计数,因为
pickle
模块不支持本地函数

选项2:用于酸洗(将
导入腌菜
替换为
导入莳萝作为腌菜


引用:

该类不能按原样进行pickle,但可以很容易地更改以使其能够进行pickle'。直接使用
\uuuu计数器。下一步\uuuu
而不是
\u genid
本地包装器:

__ids = defaultdict(__counter.__next__)
所有的
defaultdict
count
和它的
\uuuuuuuuuuuuuuuu
方法都可以被pickle,从而也可以对结果对象进行pickle