voodoo: modifying class methods a posteriori

Alex Martelli aleax at aleax.it
Wed Sep 19 11:57:06 CEST 2001


"Paul Winkler" <slinkp23 at yahoo.com> wrote in message
news:slrn9qgcg8.13u.slinkp23 at roaddog.armsnet...
    ...
> class Decorator:
>     """An abstract Decorator class based on one posted to comp.lang.python
>     by Rainer Deyke.
>     """
>     def __init__(self, decorated):
>         self._decorated = decorated
>     def __getattr__(self, name):
>         return getattr(self._decorated, name)
>     def __call__(self, *args, **kwargs):
>         self._decorated(*args, **kwargs)
>     # Override other operators too.

While it doesn't really hurt, the explicit delegation of
__call__ and other special methods is redundant, once you
are auto-delegating via __getattr__.  Python checks for
the presence of other special methods by the same call to
__getattr__, so you'll get them "for free" -- indeed, you
need to put a guard in __getattr__ to raise an AttributeError
explicitly for any special methods you DON'T want to supply.
__setattr__ and __delattr__ are different, of course!-)


Alex






More information about the Python-list mailing list