Adding methods to an object instance

lallous lallous at lgwm.org
Fri Nov 13 11:30:19 EST 2009


Hello

class __object(object):
    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"]

Thanks,
Elias 




More information about the Python-list mailing list