[C++-sig] C coded extinsion question

Hughes, Chad O chad.hughes at pnl.gov
Mon Apr 2 17:38:43 CEST 2007


I am writing a c type extension for Python deriving from the list class (using PyList_Type.tp_init).  I have the need to overload the “+” operator (To add two numbers stored as binary lists – instead of concatenation).  I have tried the following: 

static PyMethodDef BinaryList_methods[] = {
	...
	{"__add__", (PyCFunction)BinaryList___add__, METH_VARARGS,
		PyDoc_STR("__add__(self,other) -> BinaryList")},
	...
	{NULL,	NULL},
};

This the BinaryList___add__ function is called if I use the __add__ explicitly but the list base class __add__ is called for the “+” operator, for example:

a = BinaryList([1,0,0,0])
b = BinaryList([0,0,0,1])
print a.__add__(b)  #prints [1,0,0,1]
print a + b               #prints [1,0,0,0,0,0,0,1]


I read this:
object.h -- Added tp_call member to the typeobject struct
This along with a minor change to the ceval.c allows overloading
of the function call operator for any class.

Can anyone either tell me what I am doing wrong and or give me an example of how to properly overload an operator in a c coded extension?



More information about the Cplusplus-sig mailing list