[Tutor] special object method for method calls?
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__()?
__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
<bound method Foo.bar of <__main__.Foo instance at 0x400e654c>>
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()
I hope this helps!
More information about the Tutor