我有自定义列表和字典类,这些类在Python 3.7中解开时不再起作用。
import pickle
class A(dict):
pass
class MyList(list):
def __init__(self, iterable=None, option=A):
self.option=option
if iterable:
for x in iterable:
self.append(x)
def append(self, obj):
if isinstance(obj, dict):
obj = self.option(obj)
super(MyList, self).append(obj)
def extend(self, iterable):
for item in iterable:
self.append(item)
if __name__ == '__main__':
pickle_file = 'test_pickle'
my_list = MyList([{'a': 1}])
pickle.dump(my_list, open(pickle_file, 'wb'))
loaded = pickle.load(open(pickle_file, 'rb'))
print(isinstance(loaded[0], A))
在Python 2.6到3.6上运行良好:
"C:\Program Files\Python36\python.exe" issue.py
True
但是在3.7中不再正确设置self.option
。
"C:\Program Files\Python37\python.exe" issue.py
Traceback (most recent call last):
File "issue.py", line 28, in <module>
loaded = pickle.load(open(pickle_file, 'rb'))
File "issue.py", line 21, in extend
self.append(item)
File "issue.py", line 16, in append
obj = self.option(obj)
AttributeError: 'MyList' object has no attribute 'option'
如果我要删除extend
函数,它会按预期工作。
我也尝试添加__setstate__
,但是在extend
之前未调用它,因此在这一点上option
仍未定义。
我确实必须直接从dict
和list
继承,并且我确实需要在代码中覆盖append
和extend
函数。有没有办法预先设置option
或其他解决方法?这种行为变化是否已记录在案,并且是合理的?
谢谢您的时间