Getting a dictionary from an object

Bruno Desthuilliers bdesth.quelquechose at
Sun Jul 24 14:33:10 CEST 2005

Bruno Desthuilliers a écrit :
> class Wrapper(object):
>     def __init__(self, obj):
>         self._obj = obj
>     def __getitem__(self, name):
>         return getattr(self._obj, name)

If you want the Wrapper to be more like a Decorator (ie still can use 
the Wrapper object as if it was the wrapped object), you can add this:

     def __getattr__(self, name):
         return getattr(self._obj, name)

     def __setattr__(self, name, val):
         if name == '_obj':
             super(Wrapper, self).__setattr__(name, val)
             setattr(self._obj, name, val)

The Python cookbook may have some receipes too for this kind of funny 

More information about the Python-list mailing list