找出一个PyObject方法需要多少个参数

2024-10-04 13:27:12 发布

您现在位置:Python中文网/ 问答频道 /正文

我们可以使用

PyObject *method = PyDict_GetItemString(methodsDictionary,methodName.c_str());

我想知道这个方法需要多少参数。如果函数是

^{pr2}$

我怎么知道它需要两个参数?在


Tags: 方法函数参数methodpyobjectstrpydictpr2
1条回答
网友
1楼 · 发布于 2024-10-04 13:27:12

通过乔恩提供的链接。假设您不想(或不能)在您的应用程序中使用Boost,下面的代码应该可以得到这个数字(很容易从How to find the number of parameters to a Python function from C?改编):

PyObject *key, *value;
int pos = 0;
while(PyDict_Next(methodsDictionary, &pos, &key, &value)) {
    if(PyCallable_Check(value)) {
        PyObject* fc = PyObject_GetAttrString(value, "func_code");
        if(fc) {
            PyObject* ac = PyObject_GetAttrString(fc, "co_argcount");
            if(ac) {
               const int count = PyInt_AsLong(ac);
               // we now have the argument count, do something with this function
               Py_DECREF(ac);
            }
            Py_DECREF(fc);
        }
    }
}

如果您使用的是python2.x,那么上面的方法肯定有效。在python3.0+中,您似乎需要在上面的片段中使用"__code__",而不是{}。在

我很欣赏不能使用Boost(我的公司不允许我最近从事的项目),但总的来说,如果你能的话,我会尽力使用它,因为我发现pythoncapi通常会在您尝试执行类似这样复杂的事情时变得有点笨拙。在

相关问题 更多 >