Confusion about __call__ and attribute lookup

K

Kent Johnson

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:
... def __call__(self):
... print 'Called Foo'
...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
 
L

Leif K-Brooks

Kent said:
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:
... def __invert__(self):
... return 'foo'
... Traceback (most recent call last):
'foo'
 
K

Kent Johnson

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

For my future reference, is this documented somewhere in the standard docs?

Thanks,
Kent
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,982
Messages
2,570,185
Members
46,736
Latest member
AdolphBig6

Latest Threads

Top