[Tutor] special object method for method calls?

Danny Yoo dyoo at hkn.eecs.berkeley.edu
Tue Nov 11 19:16:47 EST 2003

On Tue, 11 Nov 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__()?

Hi Lance,

__getattr__() applies equally well to methods as well as other attributes.
When Python sees something like:


Python will first do a getattr() of 'bar' from foo.  Once it gets the
attribute, it'll __call__() that attribute.

>>> class Foo:
...     def bar(self): print "hi!"
>>> foo = Foo()
>>> bar = foo.bar
>>> bar
<bound method Foo.bar of <__main__.Foo instance at 0x400e654c>>
>>> bar()

Python's uniform object system is pretty nice, though it means that we
have to be careful that our regular attribute names don't collide with our
method names, since they share the same namespace within our instance.

Anyway, since attribute access goes through __getattr__(), we can do
something like this:

>>> class DoubleTalk:
...     def __getattr__(self, attr):
...         def function():
...             print attr, attr
...         return function
>>> d = DoubleTalk()
>>> d.jump()
jump jump
>>> d.leap()
leap leap
>>> d.hello()
hello hello

I hope this helps!

More information about the Tutor mailing list