Python 中字典转对象演示
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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