How to change the superclass of an instance?

Alex Martelli aleaxit at yahoo.com
Mon Sep 13 18:40:34 EDT 2004


Alexander Stante <alex_stante at yahoo.de> wrote:
   ...
> An other idea I had would be wrapping a class around the Surface
> returned by display.set_mode() and then intercepting attribute
> references with __getattr__ on that class and if not found in class or

Best (but, only attributes not found otherwise go to __getattr__, so, no
need for you to duplicate such checks).

> instance, delegate them to the Surface. I think this way it would look
> liked the wrapping class is a subclass of Surface. But Surface don't
> have a __dict__ and I don't know an other way to call a function by his
> name.

class generic_wrapper_base(object):
    def __init__(self, wrappee): self.__dict__['_w'] = wrappee
    def __getattr__(self, n): return getattr(self._w, n)
    def __setattr__(self, n, v): setattr(self._w, n, v)
    def __delattr__(self, n): delattr(self._w, n)

No need for the wrappee to have a __dict__: getattr, setattr and delattr
are the built-in functions you need.  Happy wrapping!-)


Alex



More information about the Python-list mailing list