Skip to content

Instantly share code, notes, and snippets.

@mayneyao
Created July 19, 2019 02:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mayneyao/6a09bd97237f23c0cb68730715b21851 to your computer and use it in GitHub Desktop.
Save mayneyao/6a09bd97237f23c0cb68730715b21851 to your computer and use it in GitHub Desktop.
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