====== Conversion d'objet en dict et inversement ======
* [[http://kiennt.com/blog/2012/06/14/python-object-and-dictionary-convertion.html|Source]]
===== Conversion d'un objet en dict =====
#!/usr/bin/env python
class Person(object):
def __init__(self, age, name):
self.age = age
self.name = name
**__Exemple :__**
>>> a = Person('GigiX', 30)
>>> a.__dict__
{ 'name' : 'GigiX', 'age' : 30 }
==== Conversion d'un dict en objet ====
#!/usr/bin/env python
class Struct(object):
def __init__(self, adict):
"""Convert a dictionary to a class
@param :adict Dictionary
"""
self.__dict__.update(adict)
for k, v in adict.items():
if isinstance(v, dict):
self.__dict__[k] = Struct(v)
def get_object(adict):
"""Convert a dictionary to a class
@param :adict Dictionary
@return :class:Struct
"""
return Struct(adict)
**__Exemple :__**
>>> a={ 'name': 'GigiX', 'age' : 30, 'x' : {'a' : [1,2,3]} }
>>> b=get_object(a)
>>> b.x.a
[1, 2, 3]
>>> b.name
GigiX