Confusion about __call__ and attribute lookup

Leif K-Brooks eurleif at ecritters.biz
Thu Nov 10 09:34:04 EST 2005


Kent Johnson wrote:
> 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?

New-style classes look up special methods on the class, not on the instance:

 >>> class Foo(object):
 ...     def __invert__(self):
 ...         return 'foo'
 ...
 >>> x = Foo()
 >>> ~x
 'foo'
 >>> x.__invert__ = 123
 >>> x.__invert__()
 Traceback (most recent call last):
   File "<stdin>", line 1, in ?
 TypeError: 'int' object is not callable
 >>> ~x # equivalent to type(x).__invert__()
 'foo'



More information about the Python-list mailing list