我正在开发一个使用 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/