Adding methods to an object instance

lallous lallous at
Fri Nov 13 17:30:19 CET 2009


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"]


More information about the Python-list mailing list