免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 1553 | 回复: 1
打印 上一主题 下一主题

请帮我看个python cookbook上的例子 [复制链接]

论坛徽章:
13
CU大牛徽章
日期:2013-03-14 14:14:082016科比退役纪念章
日期:2016-07-22 11:15:35数据库技术版块每日发帖之星
日期:2016-05-27 06:20:002015亚冠之吉达阿赫利
日期:2015-08-05 10:06:542015年亚洲杯之韩国
日期:2015-04-01 16:05:42双鱼座
日期:2014-11-13 11:04:24丑牛
日期:2014-07-25 17:29:54子鼠
日期:2014-04-25 12:25:45丑牛
日期:2014-04-17 08:35:48巨蟹座
日期:2014-04-16 16:50:05CU大牛徽章
日期:2013-03-14 14:14:29CU大牛徽章
日期:2013-03-14 14:14:26
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2016-10-03 11:54 |只看该作者 |倒序浏览
将一个object 转化成json, 然后将这个json 再转成object 的例子。

  1. #--------------------------------------------
  2. class Point:
  3.     def __init__(self, x, y):
  4.         self.x=x
  5.         self.y=y


  6. def serialize_instance(obj):
  7.     d={'__classname__': type(obj).__name__}
  8.     d.update(vars(obj))
  9.     return d


  10. #Dictionary mapping names to known classes
  11. classes={
  12.     'Point':Point,
  13.     }

  14. def unserialize_object(d):
  15.     clsname=d.pop('__classname__',None)
  16.     if clsname:
  17.         cls=classes[clsname]
  18.         obj=cls.__new__(cls)        #make instance without calling __init__
  19.         for key, value in d.items():
  20.             setattr(obj, key, value)
  21.             return obj
  22.     else:
  23.         return d

  24. import time
  25. def put_together():
  26.     p=Point(2,3)
  27.     s=json.dumps(p, default=serialize_instance)
  28.     print(s)
  29.     a=json.loads(s, object_hook=unserialize_object)
  30.     print(a)
  31. print(a.y)
  32.     print(a.x)   

  33. put_together()
复制代码
代码就是这样了,但是我实际运行中发现很奇怪的事情。

  1. root@kali:/root/py# ./json_1.py
  2. {"x": 2, "y": 3, "__classname__": "Point"}
  3. <__main__.Point object at 0x7ff3d7876f98>
  4. Traceback (most recent call last):
  5.   File "./json_1.py", line 114, in <module>
  6.     put_together()
  7.   File "./json_1.py", line 111, in put_together
  8.     print(a.y)
  9. AttributeError: 'Point' object has no attribute 'y'
复制代码



论坛徽章:
1
15-16赛季CBA联赛之新疆
日期:2017-03-09 12:33:45
2 [报告]
发表于 2016-10-03 20:38 |只看该作者
回复 1# hmchzb19

  1. #! python3
  2. #--------------------------------------------
  3. import sys
  4. class Utf8Encode:
  5.     def __dict_utf8(self,val):
  6.         newdict =dict()
  7.         for k in val.keys():
  8.             newk = self.__encode_utf8(k)
  9.             newv = self.__encode_utf8(val[k])
  10.             newdict[newk] = newv
  11.         return newdict

  12.     def __list_utf8(self,val):
  13.         newlist = []
  14.         for k in val:
  15.             newk = self.__encode_utf8(k)
  16.             newlist.append(newk)
  17.         return newlist

  18.     def __encode_utf8(self,val):
  19.         retval = val

  20.         if sys.version[0]=='2' and isinstance(val,unicode):
  21.             retval = val.encode('utf8')
  22.         elif isinstance(val,dict):
  23.             retval = self.__dict_utf8(val)
  24.         elif isinstance(val,list):
  25.             retval = self.__list_utf8(val)
  26.         return retval

  27.     def __init__(self,val):
  28.         self.__val = self.__encode_utf8(val)
  29.         return

  30.     def __str__(self):
  31.         return self.__val

  32.     def __repr__(self):
  33.         return self.__val
  34.     def get_val(self):
  35.         return self.__val


  36. class Point:
  37.     def __init__(self, x=0, y=0):
  38.         self.x=x
  39.         self.y=y
  40.         return


  41. def serialize_instance(obj):
  42.     d={'__classname__': obj.__class__.__name__}
  43.     d.update(vars(obj))
  44.     return d


  45. def unserialize_object(d):
  46.     d = Utf8Encode(d).get_val()
  47.     clsname=d.pop('__classname__',None)
  48.     if clsname:
  49.         cls=sys.modules[__name__].__dict__[clsname]
  50.         obj=cls()        #make instance without calling __init__
  51.         for k in d.keys():
  52.             setattr(obj, k,d[k])
  53.         return obj
  54.     else:
  55.         return d

  56. import time
  57. import json
  58. def put_together():
  59.     p=Point(2,3)
  60.     s=json.dumps(p, default=serialize_instance)
  61.     print(s)
  62.     a=json.loads(s, object_hook=unserialize_object)
  63.     print(a)
  64.     print(a.y)
  65.     print(a.x)

  66. put_together()
复制代码
修改了你的代码,这些代码在python2 python3 都已经测试通过了。
其中的Utf8Encode 是为了使python2 可以在json使用的unicode情况下也可以使用。

您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP