Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #2817

Replacing *instance* dict

From andrew cooke <andrew@acooke.org>
Newsgroups comp.lang.python
Subject Replacing *instance* dict
Date 2011-04-07 16:47 -0700
Organization http://groups.google.com
Message-ID <c7ae6804-5500-43f2-8a75-be2950110c8e@glegroupsg2000goo.googlegroups.com> (permalink)

Show all headers | View raw


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]

Back to comp.lang.python | Previous | Next | Find similar


Thread

Replacing *instance* dict andrew cooke <andrew@acooke.org> - 2011-04-07 16:47 -0700

csiph-web