automatic accessors to a member var dict elements?
Bengt Richter
bokr at oz.net
Thu Oct 14 22:26:34 EDT 2004
On Thu, 14 Oct 2004 17:56:09 -0700, Jeff Shannon <jeff at ccvcorp.com> wrote:
[...]
>
>If you really do need to maintain the dict separately, then you can use
>__getattr__() and __setattr__() to redirect accesses of nonexistent
>attributes into operations on your contained dict, something like this
>(untested):
>
> class MyClass(object): # ensure a new-style class
> def __init__(self):
> self.m_dict = {'one':1, 'two':2, 'three':3}
> def __getattr__(self, attr):
try: return self.m_dict[attr]
except KeyError: raise AttributeError(attr)
> value = self.m_dict.get(attr, None)
> if value is None:
> raise AttributeError(attr)
> return value
> def __setattr__(self, attr, value):
> self.m_dict[attr] = value
>
>I'm using a new-style class to take advantage of improvements in
>attribute lookup. For this class, __getattr__()/__setattr__() will only
>be called if attr isn't found through the normal attribute resolution
>rules.
>
>One problem with the way I'm doing things here is that, if you set a
>dict item to a value of None, the object will raise an AttributeError
>when trying to access that item. This really ought to use a safer
>sentinel value. (Check for a recent thread here in c.l.py about
>sentinel values and the use of object() as one.)
>
Why not (untested) avoid the default sentinel and just translate
a key error to an attribute error as above?
Regards,
Bengt Richter
More information about the Python-list
mailing list