[Tutor] Re: special object method for method calls?
Abel Daniel
abli at freemail.hu
Tue Nov 11 19:51:23 EST 2003
Lance E Sloan writes:
> 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__()?
See http://python.org/doc/current/ref/callable-types.html
Note that the _method's_ __call__ method will be called, not the
class's, so its not exactly what you wanted. However, it's pretty easy
to fake it:
class A:
def __getattr__(self, name):
def f(*a, **kw):
self.notify()
print 'called %s' % name
return f
def notify(self):
print 'our method was called'
>>> a=A()
>>> a.foo()
our method was called
called foo
>>> a.bar
<function f at 0x40214e64>
>>> a.zork()
our method was called
called zork
>>> f=a.bar
>>> f()
our method was called
called bar
>>>
--
Abel Daniel
p.s. you might also want to look at
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/198078
(I have to admit I have no idea how that works.)
More information about the Tutor
mailing list