customized instance dictionaries, anyone?
wolfgang.lipp at gmail.com
wolfgang.lipp at gmail.com
Wed Jan 25 12:35:50 EST 2006
thx! indeed, it worked -- took me some time to figure out how to
implement the setting of attributes, too. i finally managed to get that
done using super:
custom dictionary, unchanged::
class CustomDict( dict ):
defaultValue = 'THIS ITEM NOT AVAILABLE'
def __getitem__( self, name ):
#print 'CustomDict.__getitem__( %r )' % ( name, )
try:
return super( CustomDict, self ).__getitem__( name )
except KeyError:
return self.defaultValue
def __contains__( self, name ):
return True
def has_key( self, name ):
return True
dictionary user class::
class X( object ):
def __init__( self ):
#print 'X.__init__()'
self._dict = CustomDict( foo = 'bar' )
@property
def __dict__( self ):
#print 'X.__dict__ ( get() )'
return self._dict
def __getattr__( self, name ):
#print 'X.__getattr__( %r )' % ( name, )
return self.__dict__[ name ]
def __setattr__( self, name, value ):
#print 'X.__setattr__( %r, %r )' % ( name, value, )
if name == '_dict':
return super( X, self ).__setattr__( name, value )
self._dict[ name ] = value
the ``~.__setattr__()`` method tests for the special name ``_dict`` and
defers execution to the super of the ``X`` instance, ``object``. other
stuff is handled by the instance itself.
testing that with ::
x = X()
print x.__dict__[ 'foo' ]
print x.__dict__[ 'bar' ]
print x.foo
print x.bar
print x.__dict__
x.oops = 42
print x.__dict__
yields ::
bar
THIS ITEM NOT AVAILABLE
bar
THIS ITEM NOT AVAILABLE
{'foo': 'bar'}
{'foo': 'bar', 'oops': 42}
as expected.
i tried to reason *why* the usage of a property makes this particular
piece of code work, but i seemingly can't find out. anyone around who
has thoughts on that?
_wolfgang
More information about the Python-list
mailing list