Replacing *instance* dict

Discussion in 'Python' started by andrew cooke, Apr 8, 2011.

  1. andrew cooke

    andrew cooke Guest

    Related to the above, Is there anything wrong with the following code to replace the *instance* rather than the class dict? It seems very crude, but appears to work.

    Thanks,
    Andrew


    class TupleSuper:

    def __new__(cls):
    print('in new')
    instance = object.__new__(cls)
    instance.__dict__ = TupleDict(instance.__dict__)
    return instance


    class D(TupleSuper):

    def __init__(self):
    self.a = 1


    if __name__ == '__main__':
    d = D()
    assert d.a == 1
    d.a = 2
    assert d.a == 2
    d.a = 'three'
    assert d.a == 'three'
    print('woop')



    On Thursday, April 7, 2011 7:31:16 PM UTC-3, andrew cooke wrote:
    >
    > class TupleDict(dict):
    > '''Stores additional info, but removes it on __getitem__().'''
    >
    > def __setitem__(self, key, value):
    > print('setting', key, value)
    > super(TupleDict, self).__setitem__(key, (value, 'secret'))
    >
    > def __getitem__(self, key):
    > value = super(TupleDict, self).__getitem__(key)
    > print('getting', key, value[0]) # drop secret
    > return value[0]
    andrew cooke, Apr 8, 2011
    #1
    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. Skip Montanaro
    Replies:
    0
    Views:
    399
    Skip Montanaro
    Aug 15, 2003
  2. Alexander Kozlovsky

    dict!ident as equivalent of dict["ident"]

    Alexander Kozlovsky, May 21, 2006, in forum: Python
    Replies:
    5
    Views:
    342
    Alexander Kozlovsky
    May 22, 2006
  3. Paul Melis

    dict.has_key(x) versus 'x in dict'

    Paul Melis, Dec 6, 2006, in forum: Python
    Replies:
    48
    Views:
    1,286
    Kent Johnson
    Dec 15, 2006
  4. Almad
    Replies:
    8
    Views:
    386
    Terry Reedy
    Dec 14, 2006
  5. Rob Meade

    Replacing - and not Replacing...

    Rob Meade, Apr 5, 2005, in forum: ASP General
    Replies:
    5
    Views:
    251
    Chris Hohmann
    Apr 11, 2005
Loading...

Share This Page