我试图使用Python 3.5 C API来执行一些代码,其中包括构造类。具体来说:
class MyClass:
def test(self):
print('test')
MyClass().test()
我的问题是它的错误如下:
^{pr2}$因此,我需要我的模块包含__build_class__
,但我不确定如何(我猜我也会错过使用Python时默认得到的其他东西)-有没有方法在我的模块中包含所有这些内置的东西?在
以下是我目前为止的代码:
#include <Python.h>
int main(void)
{
int ret = 0;
PyObject *pValue, *pModule, *pGlobal, *pLocal;
Py_Initialize();
pGlobal = PyDict_New();
pModule = PyModule_New("mymod");
pLocal = PyModule_GetDict(pModule);
pValue = PyRun_String(
"class MyClass:\n\tdef test(self):\n\t\tprint('test')\n\nMyClass().test()",
Py_file_input,
pGlobal,
pLocal);
if (pValue == NULL) {
if (PyErr_Occurred()) {
PyErr_Print();
}
ret = 1;
} else {
Py_DECREF(pValue);
}
Py_Finalize();
return ret;
}
所以pValue
是{
他们(至少)有两种方法可以解决这个问题。。。在
方法1
而不是:
您可以导入
^{pr2}$__main__
模块并获得它的globals字典,如下所示:这样描述:
这是我从这个问题得到的。在
方式2
或者作为另一种选择,我个人更喜欢导入主模块(找到了here),您可以这样做,用内置的东西填充您创建的新字典,其中包括
__build_class__
:相关问题 更多 >
编程相关推荐