python-class对象-字典-格式互转

把class对象转为dict,或者把dict转为class对象

把对象转为字典

1
2
3
4
def convert_to_dict(obj):
dic = {}
dic.update(obj.__dict__)
return dic

把字典转为class对象

通过type动态创建类,type()函数依次传入3个参数:

  • class的名称,字符串形式
  • 继承的父类集合,由于python支持多重继承,如果只有一个父类,需要注意tuple的单元素写法(添加逗号)
  • class 的方法名与函数绑定, 这我们没有使用方法,而是传入的字典参数
    1
    2
    3
    4
    5
    def obj_to_dic(dic):
    top = type('TempObj', (object,), dic)
    setattr(top, dic.keys()[0], d.get(dic.keys()[0]))
    return top

测试

1
2
3
4
5
6
7
class Student:
name = ''
age = 0
def __init__(self, name, age):
self.name = name
self.age = age
1
2
3
4
5
stu = Student('Layne', 30)
print convert_to_dict(stu)
dic = {'age': 30, 'name': 'Layne'}
print obj_to_dic(dic)