python多級復合物件與字典型別互轉

2021-09-24 17:42:16 字數 2298 閱讀 2524

@staticmethod

def get_types():

base_type =

list_type =

dict_type =

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 =

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大神幫忙看看會不會記憶體洩漏

Python字典物件實現原理

字典型別是python中最常用的資料型別之一,它是乙個鍵值對的集合,字典通過鍵來索引,關聯到相對的值,理論上它的查詢複雜度是 o 1 d d c 3 d 在字串的實現原理文章中,曾經出現過字典物件用於intern操作,那麼字典的內部結構是怎樣的呢?pydictobject物件就是dict的內部實現。...

Python字典物件實現原理

字典型別是python中最常用的資料型別之一,它是乙個鍵值對的集合,字典通過鍵來索引,關聯到相對的值,理論上它的查詢複雜度是 o 1 d d c 3 d 在字串的實現原理文章中,曾經出現過字典物件用於intern操作,那麼字典的內部結構是怎樣的呢?pydictobject物件就是dict的內部實現。...

Python字典轉物件定義

新類重新賦值轉化法 先建乙個新類 dict class dict dict setattr dict.setitem getattr dict.getitem 該類整合了原字典 dict 類,字典不能使用點呼叫屬性,而該類可以,於是我們做值的轉換 def dicttoobj dictobj if n...