By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
439,931 Members | 2,015 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 439,931 IT Pros & Developers. It's quick & easy.

New-style classes and special methods

P: n/a
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
May 30 '07 #1
Share this Question
Share on Google+
1 Reply


P: n/a
Raj B <ra**@rice.eduwrote:
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
May 30 '07 #2

This discussion thread is closed

Replies have been disabled for this discussion.