Confusion about __call__ and attribute lookup

Kent Johnson kent37 at tds.net
Thu Nov 10 08:24:16 EST 2005


I am learning about metaclasses and there is something that confuses me.

I understand that if I define a __call__ method for a class, then instances of the class become callable using function syntax:

 >>> class Foo(object):
 ...   def __call__(self):
 ...     print 'Called Foo'
 ...
 >>> f=Foo()
 >>> f()
Called Foo

To create a class instance, you call the class. This made me think that the class' class must define __call__, and indeed it does, and calling it as an unbound method also creates a class instance:

 >>> dir(type)
[..., '__call__', ...]
 >>> f=type.__call__(Foo)
 >>> f
<__main__.Foo object at 0x00A35EB0>

But why doesn't Foo.__call__ shadow type.__call__? Normally an instance attribute takes precedence over a class attribute. Is it something special about how function call syntax is handled internally, or do all special methods work this way, or is there something else going on?

PS Is there any place in the standard Python docs where the details of attribute lookup are spelled out?

Thanks,
Kent



More information about the Python-list mailing list