New-style classes and special methods
Alex Martelli
aleax at mac.com
Wed May 30 11:00:25 EDT 2007
Raj B <rajb at rice.edu> wrote:
> 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
More information about the Python-list
mailing list