找回密码
 立即注册

扫一扫,访问微社区

QQ登录

只需一步,快速开始

查看: 4317|回复: 1

[已解决] 求大神指点,keywords must be strings ?

0

主题

4

帖子

4

积分

贫民

积分
4
alison 发表于 2019-2-22 21:33:43 | 显示全部楼层 |阅读模式
本帖最后由 alison 于 2019-2-22 21:54 编辑

练习json module的时候,出现keywords must be strings 错误,求大神指点一二!


  1. import json


  2. class Person(object):
  3.     def __init__(self, name, age):
  4.         self.name = name
  5.         self.age = age

  6.     def __repr__(self):
  7.         return 'Person Object name : %s , age : %d' % (self.name, self.age)


  8. def object2dict(obj):
  9.     '''
  10.     convert Person to dict
  11.     '''
  12.     d = {}
  13.     d['__class__'] = obj.__class__.__name__
  14.     d['__module__'] = obj.__module__
  15.     d.update(obj.__dict__)
  16.     return d


  17. def dict2object(d):
  18.     '''
  19.     convert dict ot Person
  20.     '''
  21.     if '__class__' in d:
  22.         class_name = d.pop('__class__')
  23.         module_name = d.pop('__module__')
  24.         module = __import__(module_name)
  25.         class_ = getattr(module, class_name)
  26.         args = dict((key.encode('ascii'), value) for key, value in d.items())  # get args
  27.         print(args)
  28.         inst = class_(**args)  # create new instance
  29.     else:
  30.         inst = d
  31.     return inst


  32. if __name__ == '__main__':
  33.     p = Person('alison', 40)
  34.     print(p)
  35.     d = object2dict(p)
  36.     print(d)
  37.     o = dict2object(d)
  38.     print(type(o), o)

  39.     dump = json.dumps(p, default=object2dict)
  40.     print(dump)
  41.     load = json.loads(dump, object_hook=dict2object)
  42.     print(load)
复制代码



报错:  

Traceback (most recent call last):
{'__class__': 'Person', '__module__': '__main__', 'name': 'alison', 'age': 40}
{b'name': 'alison', b'age': 40}
  File "G:/workspace/PycharmProjects/module/jsonDemo.py", line 52, in <module>
    o = dict2object(d)
  File "G:/workspace/PycharmProjects/module/jsonDemo.py", line 41, in dict2object
    inst = class_(**args)  # create new instance
TypeError: __init__() keywords must be strings

回复

使用道具 举报

0

主题

4

帖子

4

积分

贫民

积分
4
alison  楼主| 发表于 2019-2-22 21:55:39 | 显示全部楼层
原来的逆向传参!!!
回复 支持 反对

使用道具 举报

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

本版积分规则

快速回复 返回顶部 返回列表