gpt4 book ai didi

python - Python 3 中的 PyClass_New 等价物是什么?

转载 作者:太空狗 更新时间:2023-10-30 00:02:34 27 4
gpt4 key购买 nike

之前我使用 C API 创建了一些 Python 类。当我要用 Python 3+ 构建旧项目时,它会出现以下编译错误

PyClass_New was not declared in this scopePy_InitModule was not declared in this scope

What are the equivalents?

PyObject *pClassDic = PyDict_New();
PyObject *pClassName = PyBytes_FromString("MyClass");
PyObject *pClass = PyClass_New(NULL, pClassDic, pClassName);

最佳答案

如果您不想经历设置对象和类型结构的麻烦,您应该能够通过调用 Python 的 type(name, bases, dict) 创建一个新类来自 C:

PyObject *pClassName = PyBytes_FromString("MyClass");
PyObject *pClassBases = PyTuple_New(0); // An empty tuple for bases is equivalent to `(object,)`
PyObject *pClassDic = PyDict_New();

// pClass = type(pClassName, pClassBases, pClassDic)
PyObject *pClass = PyObject_CallFunctionObjArgs(PyType_Type, pClassName, pClassBases, pClassDic, NULL);

Py_CLEAR(pClassName);
Py_CLEAR(pClassBases);
Py_CLEAR(pClassDic);

关于python - Python 3 中的 PyClass_New 等价物是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29301824/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com