我需要确保dict
只能接受某种类型的对象作为值。它也必须是可挑选的。
这是我的第一次尝试:
import pickle
class TypedDict(dict):
_dict_type = None
def __init__(self, dict_type, *args, **kwargs):
super().__init__(*args, **kwargs)
self._dict_type = dict_type
def __setitem__(self, key, value):
if not isinstance(value, self._dict_type):
raise TypeError('Wrong type')
super().__setitem__(key, value)
如果我用下面的代码测试它(python 3.5)
my_dict = TypedDict(int)
my_dict['foo'] = 98
with open('out.pkl', 'wb') as fin:
pickle.dump(my_dict, fin)
with open('out.pkl', 'rb') as fin:
out = pickle.load(fin)
我收到错误:TypeError: isinstance() arg 2 must be a type or tuple of types
.
似乎没有加载正确的值_dict_type
它改为使用默认值None
.
另外,它似乎依赖于协议,就好像它可以正常工作一样protocol=0
但是,如果我覆盖__reduce__
方法并调用 super 一切都会神奇地起作用。
def __reduce__(self):
return super().__reduce__()
怎么可能呢?不应该是两个类(w/o__reduce__
) 相等的?我缺少什么?