When creating a class in Python, I can simply make a def __len__(self):
method to make the len(InstanceOfMyClass)
work, however I can't find out how to do this with an extension class via the C-API.
I tried adding a __len__
method, but that appears to not work
{"__len__",(PyCFunction)&TestClass_GetLen,METH_NOARGS,""},
Python test code:
def test(my_instance):
x = len(my_instance)#exception
return x
TypeError: object of type 'test_module.test_class' has no len()
Code for TestClass
struct TestClass;
static int TestClass_Init(TestClass *self, PyObject *args, PyObject* kwds);
static void TestClass_Dealloc(TestClass *self);
static PyObject* TestClass_GetLen(TestClass *self);
struct TestClass
{
PyObject_HEAD;
};
static PyMethodDef TestClass_methods[] =
{
{"__len__",(PyCFunction)&TestClass_GetLen,METH_O,""},
{NULL}
};
static PyTypeObject TestClass_type = {PyObject_HEAD_INIT(NULL)};
bool InitTestClass(PyObject *module)
{
TestClass_type.tp_basicsize = sizeof(TestClass);
TestClass_type.tp_name = PY_MODULE_NAME".TestClass";
TestClass_type.tp_doc = "";
TestClass_type.tp_flags = Py_TPFLAGS_DEFAULT;
TestClass_type.tp_methods = TestClass_methods;
TestClass_type.tp_new = PyType_GenericNew;
TestClass_type.tp_init = (initproc)TestClass_Init;
TestClass_type.tp_dealloc = (destructor)TestClass_Dealloc;
if(PyType_Ready(TestClass_type) < 0) return false;
Py_INCREF(TestClass_type);
PyModule_AddObject(module, "TestClass", (PyObject*)&TestClass_type);
return true;
};
void TestClass_Dealloc(TestClass *self)
{
Py_TYPE(self)->tp_free((PyObject*)self);
}
int TestClass_Init(TestClass *self, PyObject *args, PyObject* kwds)
{
return 0;
}
PyObject* TestClass_GetLen(TestClass *self)
{
return PyLong_FromLong(55);
}