Adding methods to an object instance

Bruno Desthuilliers bruno.42.desthuilliers at websiteburo.invalid
Fri Nov 13 11:47:02 EST 2009


lallous a écrit :
> Hello
> 
> class __object(object):

<ot>
the convention for reusing reserved words as identifiers is to *suffix* 
them with a single underscore, ie:

class object_(object):
    #
</ot>

>    def __getitem__(self, idx):
>        return getattr(self, idx)
> 
> class __dobject(object): pass
> 
> x = __object()
> setattr(x, "0", "hello")
> print x["0"]
> 
> y = __dobject(a=1,b=2)
> 
> setattr(y, "0", "world")
> #print y["0"]
> 
> How can I, given an object of instance "__dobject", add to that instance 
> a __getitem__ method so that I can type:
> print y["0"]

Adding per-instance methods won't work for __magic_methods__. But you 
could use the Decorator pattern here:


class IndexableDecorator(object):
     def __init__(self, other):
         self._other = other
     def __getitem__(self, idx):
         return getattr(self._other, idx)
     def __setattr__(self, name, value):
         if name = "_other":
             object.__setattr__(self, name, value)
         else:
             setattr(self._other, name, value)

x = IndexableDecorator(x)

NB : not tested, so it probably contains at least one obvious error !-)



More information about the Python-list mailing list