dictionary - How to convert Python dict to a specifically-typed object? -
dictionary - How to convert Python dict to a specifically-typed object? -
using python 2.7 need convert dictionary typed object.
for illustration if have dict :
mapy = {'id': 1, 'name': 'bob'}
i need way generate class @ runtime given previous map , type name (which 'person'
in example):
class person: def __init__(self): self.id = id self.name = name
should consider using meta-programming techniques , if 1 (decorators, metaclasses, ...)?
please note don't need convert dict object; need attach type info resulting object.
you can utilize next function generate __init__
method based on given dict
:
def make_init(d): def __init__(self, **kwargs): name in d: setattr(self, name, kwargs[name]) homecoming __init__
then, utilize 3-argument form of type
create class @ run-time.
type_name = "person" person = type(type_name, (object,), { '__init__': make_init(mapy) })
finally, instantiate class using dictionary provide arguments __init__
:
obj = person(**mapy)
python dictionary metaprogramming
Comments
Post a Comment