- 论坛徽章:
- 13
|
将一个object 转化成json, 然后将这个json 再转成object 的例子。
- #--------------------------------------------
- class Point:
- def __init__(self, x, y):
- self.x=x
- self.y=y
- def serialize_instance(obj):
- d={'__classname__': type(obj).__name__}
- d.update(vars(obj))
- return d
- #Dictionary mapping names to known classes
- classes={
- 'Point':Point,
- }
- def unserialize_object(d):
- clsname=d.pop('__classname__',None)
- if clsname:
- cls=classes[clsname]
- obj=cls.__new__(cls) #make instance without calling __init__
- for key, value in d.items():
- setattr(obj, key, value)
- return obj
- else:
- return d
- import time
- def put_together():
- p=Point(2,3)
- s=json.dumps(p, default=serialize_instance)
- print(s)
- a=json.loads(s, object_hook=unserialize_object)
- print(a)
- print(a.y)
- print(a.x)
- put_together()
复制代码 代码就是这样了,但是我实际运行中发现很奇怪的事情。
- root@kali:/root/py# ./json_1.py
- {"x": 2, "y": 3, "__classname__": "Point"}
- <__main__.Point object at 0x7ff3d7876f98>
- Traceback (most recent call last):
- File "./json_1.py", line 114, in <module>
- put_together()
- File "./json_1.py", line 111, in put_together
- print(a.y)
- AttributeError: 'Point' object has no attribute 'y'
复制代码
|
|