Child
和Parent
类均从Python字典继承:
import json
class Child(dict):
def __init__(self, **kwargs):
super(Child, self).__init__(**kwargs)
class Parent(dict):
def __init__(self, **kwargs):
super(Parent, self).__init__(**kwargs)
parent = Parent(child = Child())
print type(parent['child'])
打印:
<class '__main__.Child'>
使用json.dumps
和json.loads
执行序列化和反序列化之后,Parent['child']
成为常规词典:
dumped = json.dumps(parent)
loaded = json.loads(dumped)
parent_2 = Parent(**loaded)
print type(parent_2['child'])
打印:
<type 'dict'>
问题:如何确保在序列化之后,parent_2['child']
是Child
的实例,而不是常规的Python字典?
答案 0 :(得分:2)
module.exports = {
todos: function() {return todos},
shoppingList : function {return shoppingList }
}
就是一个字典,就是这样。经过一番尝试和错误后,我发现了它。 (注意:您似乎正在使用旧版Python,因此可能需要对该解决方案进行语法调整。)
loads
如果不使用初始化为import json
class Child(dict):
def __init__(self, **kwargs):
super(Child, self).__init__(**kwargs)
class Parent(dict):
def __init__(self, **kwargs):
super(Parent, self).__init__(**kwargs)
parent = Parent(child=Child())
print(type(parent['child']))
if __name__ == '__main__':
dumped = json.dumps(parent)
loaded = json.loads(dumped)
parent_2 = Parent(child=Child(**loaded)) # Changed how you call Parent
print(type(parent_2['child']))
的{{1}}来调用Parent
的args,除非您添加其他逻辑,否则我们无法期望检测到dict
类型的来检测类型。
答案 1 :(得分:1)
您可以使用 pickle 。解开未知的腌制对象可能很危险(因为它们可能是恶意的)。
阅读文档https://docs.python.org/3/library/pickle.html 因为它包含更多信息。
import pickle
class Foo:
attr = 'A class attribute'
with open('pickle_class.pk','wb') as f:
pickle.dump(Foo,f)
# we open the file for reading
with open('pickle_class.pk','rb') as f:
Bar = pickle.load(f)
# Test if they are the same.
assert Bar==Foo,'Not the Same'
您也可以压缩。
import bz2
import pickle
with bz2.BZ2File('pickled_class', 'wb') as f:
pickle.dump(Foo, s)
在某些情况下,与使用多线程和lambda一样,第三方模块 dill 可能会在腌制时抛出问题而很方便
PicklingError: Can't pickle <function <lambda> at 0x111d0a7b8>: attribute lookup <lambda> on __main__ failed
流量和危险(破坏恶意软件)是相同的:
import dill
class Foo:
attr = 'A class attribute'
with open('pickle_class.pk','wb') as f:
dill.dump(Foo,f)
阅读莳萝文档:https://pypi.org/project/dill/
N.B:永远不会加载未知的腌制文件
答案 2 :(得分:0)
有一个名为jsonpickle的软件包。似乎可以解决问题;
import json
import jsonpickle
class Child(dict):
def __init__(self, **kwargs):
super(Child, self).__init__(**kwargs)
class Parent(dict):
def __init__(self, **kwargs):
super(Parent, self).__init__(**kwargs)
if __name__ == '__main__':
parent = Parent(child=Child())
dumped = jsonpickle.encode(parent)
loaded = jsonpickle.decode(dumped)
parent_2 = Parent(**loaded)
print(type(parent_2['child']))
<class '__main__.Child'>
注意;为此,Json将获得有关原始对象图的信息,以便可以对其进行还原。
('{"py/object": "__main__.Parent", "child": {"py/object": "__main__.Child", '
'"__dict__": {}}, "__dict__": {}}')