automatic delegation

Peter Otten __peter__ at
Tue Aug 3 13:17:14 CEST 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__().

I tried in vain to solve your problem while improving my understanding of
metaclasses. I have made an observation that might interest you, though: 
str(foo()) and foo.__str__(foo()) are not the same:

>>> class Type(type):
...     def __getattribute__(self, name):
...             def tostr(self):
...                     return "so what"
...             return tostr
>>> class C:
...     __metaclass__ = Type
>>> print str(C())
<__main__.C object at 0x40296a8c>
>>> print C.__str__(C())
so what

Care to explain, anyone?


More information about the Python-list mailing list