Replacing *instance* dict
andrew cooke
andrew at acooke.org
Thu Apr 7 19:47:37 EDT 2011
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]
More information about the Python-list
mailing list