automatic delegation

Yermat loic at fejoz.net
Tue Aug 3 08:37:53 EDT 2004


Hallvard B Furuseth wrote:
> Is it possible to write a metaclass or something so that
> with a class definition not much larger than this:
> 
>    class foo:
>       def __init__(self, val): self.val = val
> 
> operations on a foo instance f will be applied to f.val?
> E.g. str(f) -> f.__str__() -> f.val.__str__().
> 

Here a simple example :

class proxy(object):
     def __init__(self, obj):
         self.obj = obj

     def __getattr__(self, key):
         if key in self.__dict__:
             return self.__dict__[key]
         else:
             return getattr(self.obj, key)

You can also look at:
http://www.python.org/cgi-bin/moinmoin/ProxyProgramming

-- 
Yermat




More information about the Python-list mailing list