Adding methods to an object instance

Discussion in 'Python' started by lallous, Nov 13, 2009.

  1. lallous

    lallous Guest

    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
     
    lallous, Nov 13, 2009
    #1
    1. Advertising

  2. 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 !-)
     
    Bruno Desthuilliers, Nov 13, 2009
    #2
    1. Advertising

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

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Neo
    Replies:
    1
    Views:
    550
    Scott Allen
    Jan 7, 2005
  2. John M. Gabriele
    Replies:
    18
    Views:
    1,225
    Steven Bethard
    Feb 18, 2005
  3. Leon Bogaert
    Replies:
    19
    Views:
    360
    Robert Klemme
    Mar 23, 2008
  4. Raj Singh
    Replies:
    2
    Views:
    218
    Rick DeNatale
    May 29, 2008
  5. Kenneth McDonald
    Replies:
    5
    Views:
    387
    Kenneth McDonald
    Sep 26, 2008
Loading...

Share This Page