@staticmethod
def get_types():
base_type = {int, float, bool, complex, str}
list_type = {list, tuple, set}
dict_type = {dict}
return base_type, list_type, dict_type
# 多级对象转字典
@staticmethod
def entity_to_dict(obj):
base_type, list_type, dict_type = CommonBase.get_types()
if type(obj) in dict_type:
obj_rtn = {k: CommonBase.entity_to_dict(v) for k, v in obj.items()}
elif type(obj) in list_type:
obj_rtn = [CommonBase.entity_to_dict(v) for v in obj]
elif type(obj) in base_type:
obj_rtn = obj
else:
dict_val = {}
dict_val.update(obj.__dict__)
obj_rtn = CommonBase.entity_to_dict(dict_val)
return obj_rtn
# 字典转对象
@staticmethod
def dict_to_entity(dict_item, en=None):
if en is None:
obj_name = "obj_" + str(uuid.uuid1().int)
exec("class " + obj_name + ": pass")
target = eval(obj_name + "()")
else:
obj_name = en.__class__.__name__
target = en
base_type, list_type, dict_type = CommonBase.get_types()
for key, val in dict_item.items():
if not hasattr(target, key):
exec(obj_name + "." + key + "=None")
obj_val = getattr(target, key)
if type(val) in dict_type and type(obj_val) in dict_type:
rtn = val
elif type(val) in dict_type:
rtn = CommonBase.dict_to_entity(dict_item=val, en=obj_val)
elif type(val) in list_type:
rtn = rtn = [CommonBase.dict_to_entity(dict_item=item, en=eval(obj_val.__class__.__name__ + "()")) for item in val]
else:
rtn = val
setattr(target, key, rtn)
return target
例子
class man:
name = "james.Yu"
age = 10
oth = None
class man_info:
work = "it"
tel = 123456789
m = man()
m.oth = man_info()
d=entity_to_dict(m) # 转成字典
o = dict_to_entity(d) # 转成对象
# 当人你也可以指定对象类型,同时给下级对象一个默认值,那就不去创建对象了
class man:
name = "james.Yu"
age = 10
oth = man_info()
class man_info:
work = "it"
tel = 123456789
# 会转成man这个对象
o = dict_to_entity(d,man())
最后因为动态创建对象可能导致内存泄漏问题(我不确定)安全起见可以改一下把动态创建出来的对象缓存不用每次创建出来,我是直接让前面传我一个name过来,然后把动态对象缓存起来后用,python很久没有用了,最近因为大数据要用又重新拿起来,python大神帮忙看看会不会内存泄漏