Defining Python class methods in C

Alex Martelli aleax at aleax.it
Sun Mar 23 11:43:40 CET 2003


Bryan wrote:

> it looks like self in context_init is also NULL.  i thought that at
> __init__ time, you already have a self variable.

Yes, but a class's __init__ is called with self as the first
ORDINARY argument (in the args tuple).


> in python in nutshell, page 544, initpair is calling these two
> methods:
> 
> PyType_Ready(&t_intpair);
> PyObject_SetAttrString(this_module, "intpair", (PyObject*)&t_intpair);

That's because intpair is a type, not a class.  Unfortunately,
you still have to keep the distinction in mind at least when
programming at the C level.


> i tried something similiar, but self in both of my methods is NULL.

I think you'll probably be best advised to code your C-level
"thingy" as a type rather than a class.  But if you do want
to code it as a class instead (e.g. for compatibility to some
old version of Python) then you'll PyArg_ParseTupe with a
format of (e.g.) "Oii" when you expect your class to be called
with two integers, just as your __init__'s signature in a
Python-coded class would be "__init__(self, first, second)" --
three perfectly ordinary arguments, the first one of which, 
implcitly passed by Python, is the "self" being initialized.


Alex





More information about the Python-list mailing list