python - 是否可以为 PySequence_Fast 循环仅调用一次 PyObject_CallMethod?

标签 python python-3.x

我正在开发一个使用 Python 3.7 的“C”API 实现的 python 模块。我正在尝试加速 PySequence_Fast() 循环,该循环使用 PyObject_CallMethod() 调用函数。由于对象都是同一个 python 类,我希望避免每次解析函数名称的开销。这可能吗?

这是我正在尝试改进的(精简的)代码片段:

    PyObject *seq = PySequence_Fast(object_list,"not a sequence");
    int len = PySequence_Size(object_list);
    for ( int n = 0 ; n < len ; n++ )
    {
        PyObject *obj = PyList_GET_ITEM(seq,n);
        PyObject_CallMethod(obj,"my_function",NULL);
    }

提前致谢。

最佳答案

只需通过 C API 执行您在 Python 中执行的完全相同的操作。

在 Python 中,你将进行转换

for thing in stuff:
    thing.method()

method = ThingClass.method
for thing in stuff:
    method(thing)

因此,使用PyObject_GetAttrString 对对象的类进行属性查找以找到未绑定(bind)的方法。 , 并用 PyObject_CallObject 调用它或 PyObject_CallFunctionObjArgs或您认为最方便的任何调用方式。

关于python - 是否可以为 PySequence_Fast 循环仅调用一次 PyObject_CallMethod?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63332520/

相关文章:

python - 从字符串开头删除数字的最 Pythonic 方法是什么?

python - 有没有办法在 Keras Conv2D() 函数中设置音频数据输入矩阵的总文件数?

python - 如何使用 webdriver 作为上下文管理器

python-3.x - py2neo v3 属性错误 : object has no attribute 'db_exists'

python - 扩展分层数据,根据列中的列表项创建新行

Python:如何使用列表而不是计数器迭代字典

python - Pandas 从来自 Excel 的数据框中删除列和行

python - 使用 json 模块解码类似 JSON 的对象

python-3.x - ModuleNotFoundError 没有名为 onetimepad 的模块?

python - pycharm 中的“预期语句结束”