Adding methods to an object instance

L

lallous

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
 
B

Bruno Desthuilliers

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):
#
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 !-)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,055
Latest member
SlimSparkKetoACVReview

Latest Threads

Top