Skip to content

Instantly share code, notes, and snippets.

@mayneyao mayneyao/dict2obj.py
Created Jul 19, 2019

Embed
What would you like to do?
Python 中字典转对象演示
from types import SimpleNamespace
npc = {
'name': {
'first': 'san',
'last': 'zhang'
},
'hp': 1000
}
npc
npc = SimpleNamespace(**npc)
npc.hp
npc.name
npc.name.first
from functools import singledispatch
@singledispatch
def wrap_namespace(ob):
return ob
wrap_namespace(1)
@singledispatch
def mytype(obj):
return obj
@mytype.register(list)
def handle_list(obj):
print("i am list")
return obj
mytype([1,2,3,4])
mytype("a")
def dict2obj
@singledispatch
def dict2obj(o):
return o
@dict2obj.register(dict)
def handle_obj(obj):
return SimpleNamespace(**{ k:dict2obj(v) for k,v in obj.items() })
@dict2obj.register(list)
def handle_list(lst):
return [ dict2obj(i) for i in lst]
npc
dict2obj(npc)
zhangsan = {}
zhangsan = {'name': {'first': 'san', 'last': 'zhang'}, 'hp': 1000}
lisi = {'name': {'first': 'si', 'last': 'li'}, 'hp': 1000, 'friends': [zhangsan]}
lisi
zhangsan
lisi
obj_lisi = dict2obj(lisi)
obj_lisi.name
obj_lisi.name.first
obj_lisi.hp
obj_lisi.friends[0].name
obj_lisi.friends[0].name.first
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.