New-style classes and special methods

R

Raj B

Hi

My question is about how special methods are stored internally in
Python objects.
Consider a new-style class which implements special methods such as
__call__ and __new__

class C(type):
def __call__(...):
<body>

class B:
__metaclass__ = C
<stuff>

b= B()

The type of C is 'type', that of B is 'C'. When B is instantiated,
the __call__ method of C is first invoked, since C is the metaclass
for B.

Internally, when a Python callable object 'obj' is called, the actual
function called seems to be
'obj->ob_type->tp_call'.

Does this that somehow the '__call__' method defined in C above is
assigned to the 'tp_call' slot in the object representing the class
C, instead of it just being stored in the dictionary like a normal
attribute? Where and how does this magic happen exactly? I'd
appreciate any level of detail.

Thanks!
Raj
 
A

Alex Martelli

Raj B said:
Hi

My question is about how special methods are stored internally in
Python objects.
Consider a new-style class which implements special methods such as
__call__ and __new__

class C(type):
def __call__(...):
<body>

class B:
__metaclass__ = C
<stuff>

b= B()

The type of C is 'type', that of B is 'C'. When B is instantiated,
the __call__ method of C is first invoked, since C is the metaclass
for B.

Internally, when a Python callable object 'obj' is called, the actual
function called seems to be
'obj->ob_type->tp_call'.

Does this that somehow the '__call__' method defined in C above is
assigned to the 'tp_call' slot in the object representing the class
C, instead of it just being stored in the dictionary like a normal
attribute? Where and how does this magic happen exactly? I'd
appreciate any level of detail.

Yes, special methods populate the slots in the structures which Python
uses to represent types. Objects/typeobject.c in the Python source
distribution does the hard work, particularly in function type_new (line
1722 in my current SVN checkout).

If you're not comfortable reading C code you may want to try looking at
the "Python implemented in Python" project, pypy, or perhaps
alternatives such as Jython (in Java) or better IronPython (in C#), but
I am not familiar in detail with how they deal with the issue.


Alex
 

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,755
Messages
2,569,536
Members
45,007
Latest member
obedient dusk

Latest Threads

Top