[Tutor] special object method for method calls?

Jeff Shannon jeff at ccvcorp.com
Tue Nov 11 20:01:56 EST 2003

Lance E Sloan wrote:

> Is there a special method that's called when the method of a class is 
> called?  That is, I know __getattr__() is called when an attribute of a 
> class is requested.  Is there something like __callmethod__()?

Well, there's a builtin iscallable() function, so you could try 
something like:

def __getattr__(self, attr):
     if iscallable(self.__dict__[attr]):
         # do whatever here
     return self.__dict__[attr]

However, this isn't exactly what you asked for -- it will take that 
action whenever a callable attribute is looked up, not specifically 
when it's called.  Thus,

item.method()          # This triggers your special action
func = item.method     # and so does this
func()                 # but this doesn't

Methods are usually only looked up when they're called, and most usage 
of methods doesn't involve caching references, so there's a good 
chance that this will (at least mostly) work for your purposes...

Jeff Shannon
Credit International

More information about the Tutor mailing list