[Tutor] __callattr__ ?

Kent Johnson kent37 at tds.net
Mon Mar 30 13:45:56 CEST 2009


On Mon, Mar 30, 2009 at 5:51 AM, spir <denis.spir at free.fr> wrote:
> Hello,
>
> Is there something like a __callattr__ magic method that would catch either unknown (like __getattr__) or all (like __getattribute__) method calls?
> If not, how would you do that? Also if not, do you know why we have __getattr__, __setattr__, but no __callattr__?

Methods are just callable attributes. If you have for example

class Foo(object):
  def sayFoo(self):
    print 'foo'

f = Foo()

then sayFoo is an attribute of class Foo.

When you then write
  f.sayFoo()
what that means is,
- look up the sayFoo attribute on object f (returning the class
attribute since f has no sayFoo attribute itself)
- call the object that results

So, to intercept calls to unknown methods you use __getattr__ or
__getattribute__ just as for other attributes. For example,
In [10]: class Foo(object):
   ....:     def __getattr__(self, name):
   ....:         def show():
   ....:             print 'called', name
   ....:         return show

In [18]: f = Foo()

In [19]: f.superduper()
called superduper

Kent


More information about the Tutor mailing list