频道栏目
IT货架 > > 正文
Python map class/类结构体 相互转换
网友分享于:Aug 2, 2018 1:57:21 PM    来源: IT货架   
Python map class/类结构体 相互转换#!/usr/bin/env python #coding=utf-8 #---------------------------------------------------------------------- def obj2map(obj): """""" return vars(obj) ######################################################################## class obj: def __init__(self): self.a = 1 self.b = 2 ######################################################################## class map2struct: def __init__(self, **entries): self.__dict__.update(entries) o = obj() print '~~~~~~~~~~~~~~ obj -> map ~~~~~~~~~~~~~~' m = vars(o) print type(m), m print '~~~~~~~~~~~~~~ map -> obj ~~~~~~~~~~~~~~' o2 = map2struct(**m) print type(o2), o2 print o2.a, o2.b print '~~~~~~~~~~~~~~ map -maker-> obj ~~~~~~~~~~~~~~' from collections import namedtuple sMaker = namedtuple('structMaker', 'a b c') print sMaker s = sMaker(a=1, b={'b': 2}, c=['c', 3]) print s print s.a print s.b print s.c输出内容~~~~~~~~~~~~~~ obj -> map ~~~~~~~~~~~~~~ <type 'dict'> {'a': 1, 'b': 2} ~~~~~~~~~~~~~~ map -> obj ~~~~~~~~~~~~~~ <type 'instance'> <__main__.map2struct instance at 0x10f0c07e8> ~~~~~~~~~~~~~~ map -maker-> obj ~~~~~~~~~~~~~~ <class '__main__.structMaker'> structMaker(a=1, b={'b': 2}, c=['c', 3]) {'b': 2} ['c', 3]
相关板块推荐 Java PHP Python

广告服务联系QQ:1134687142 | 网站地图

版权所有: IT货架- 内容来自互联网,仅供用于技术学习,请遵循相关法律法规. 京ICP备11030978号-1