overloading __getattr__ and inheriting from dict
Robert Brewer
fumanchu at amor.org
Fri Mar 12 14:05:55 EST 2004
Benoît Dejean wrote:
> class TargetWrapper(dict):
>
> def __init__(self, **kwargs):
> dict.__init__(self, kwargs)
>
> __getattr__ = dict.__getitem__
> __setattr__ = dict.__setitem__
> __delattr__ = dict.__delitem__
>
> then
>
> tw = TargetWrapper()
> tw.a = "spam" # ok
> del tw.a # ok
> tw.b = "egg"
> print tw.b
>
> last line give me an
> AttributeError: 'TargetWrapper' object has no attribute 'b'
>
> if i define
>
> def __getitem__(self, name):
> return dict.__getitem__(self, name)
>
> __getattr__ = __getitem__
>
> then the accessing the b attribute is ok. what's wrong ?
Not sure (analysis is too much for my tiny brain right now), but why don't you try:
def __getattr__(self, name):
return self[name]
That's the "usual" way to override __getattr__.
FuManChu
More information about the Python-list
mailing list