简体   繁体   中英

Python C-API Making len(…) work with extension class

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);
}

As Igniacio says, the correct way is to fill the tp_as_sequence member of your typeobject. Here is a minimal example:

#include <Python.h>

/**
 * C structure and methods definitions
 */

typedef struct {
    PyObject_HEAD;
} TestObject;

static Py_ssize_t
TestClass_len(TestObject* self) 
{   
    return 55;
}

/**
 * Python definitions
 */

static PySequenceMethods TestClass_sequence_methods = {
    TestClass_len,                  /* sq_length */
};

static PyTypeObject TestClass = {
    PyObject_HEAD_INIT(NULL)    
    0,                              /*ob_size*/
    "testmodule.TestClass",         /*tp_name*/
    sizeof(TestObject),             /*tp_basicsize*/
};

/**
 * Module entry point
 */
#ifndef PyMODINIT_FUNC  /* declarations for DLL import/export */
#define PyMODINIT_FUNC void
#endif
PyMODINIT_FUNC
inittestmodule(void) 
{
    PyObject* m;

    TestClass.tp_new = PyType_GenericNew;
    TestClass.tp_as_sequence = &TestClass_sequence_methods;
    TestClass.tp_flags = Py_TPFLAGS_DEFAULT;

    if (PyType_Ready(&TestClass) < 0)
        return;

    m = Py_InitModule3("testmodule", NULL, "");

    Py_INCREF(&TestClass);
    PyModule_AddObject(m, "TestClass", (PyObject *)&TestClass);
}

Another (more complicated and slower) way is to add a __len__ method to your class dynamically in the module's init function with PyCFunction_New , PyMethod_New and PyObject_SetAttr . This would look more like the code you pasted, except that you defined __len__ in the C methods table, which doesn't work.

tp_as_sequence的typeobject结构的成员应该的东西,有其填写sq_length成员居住。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM