Overriding all methods in a class

Christian Tismer tismer at tismer.com
Fri Sep 20 17:22:32 CEST 2002


Joao Prado Maia wrote:
> Hi,
> 
> I have been looking for an answer for this question for a while, but 
> couldn't find anything that would work for what I want to do.
> 
> I know that you can use __getattr__ to overload methods that your class 
> don't have, but what about overloading all methods, so I could in a way 
> 'intercept' calls to my methods and do something different if I wanted, is 
> that possible ?
> 
> What I want to do basically is create a caching system for a specific 
> class, and have __getattr__ (or any other magic method name) handle the 
> decision to sue the cached return value or to actually call the method.
> 
> Maybe it would be just easier to rename my current class to _Classname and 
> create a new Classname with just __getattr__.
> 
> Any suggestions ?

Use the new class type, by deriving from some builtin,
and then use the new __getattribute__. For instance

class MyObject(object):
     def __getattribute__(self, name):
         print name
         return getattr(MyObject, name)

But be *very* careful, it is easy to cause endless recursions,
for instance it is not possible to use self.__class__ in
that context.

ciao - chris

-- 
Christian Tismer             :^)   <mailto:tismer at tismer.com>
Mission Impossible 5oftware  :     Have a break! Take a ride on Python's
Johannes-Niemeyer-Weg 9a     :    *Starship* http://starship.python.net/
14109 Berlin                 :     PGP key -> http://wwwkeys.pgp.net/
work +49 30 89 09 53 34  home +49 30 802 86 56  pager +49 173 24 18 776
PGP 0x57F3BF04       9064 F4E1 D754 C2FF 1619  305B C09C 5A3B 57F3 BF04
      whom do you want to sponsor today?   http://www.stackless.com/






More information about the Python-list mailing list