【发布时间】:2016-03-12 05:06:11
【问题描述】:
在 Python 中,定义内部类很简单:
class MyClass(object):
class MyInnerClass(object):
pass
... 可以按预期访问内部类,例如通过MyClass.MyInnerClass.
我正在尝试使用扩展模块设置类似的东西。通常,将定义的扩展类型添加到模块的 <modulename>init() 函数中的扩展模块对象中,代码如下:
/// …
if (PyType_Ready(&BufferModel_Type) < 0) { return; }
/// Add the BufferModel type object to the module
Py_INCREF(&BufferModel_Type);
PyModule_AddObject(module,
"Buffer",
(PyObject*)&BufferModel_Type);
/// …
为了设置内部类,我改变了这种方法,尝试添加一个PyTypeObject* 作为另一个PyTypeObject* 的属性,如下所示:
/// …
if (PyType_Ready(&ImageBufferModel_Type) < 0) { return; }
if (PyType_Ready(&ImageModel_Type) < 0) { return; }
/// Add the ImageBufferModel type object to im.Image
Py_INCREF(&ImageBufferModel_Type);
PyObject_SetAttrString((PyObject*)&ImageModel_Type,
"ImageBuffer",
(PyObject*)&ImageBufferModel_Type);
PyType_Modified((PyTypeObject*)&ImageModel_Type);
/// Add the ImageModel type object to the module
Py_INCREF(&ImageModel_Type);
PyModule_AddObject(module,
"Image",
(PyObject*)&ImageModel_Type);
/// …
…我认为PyObject_SetAttrString() 会像introduction to “Type Objects” in the C-API docs 那样工作:
类型对象可以使用任何
PyObject_*()或PyType_*()函数 […]
...我添加了基于its description in the docs 的调用PyType_Modified()。但是这样:当我编译所有内容并尝试加载扩展时,我得到了这个错误:
>>> import im
Traceback (most recent call last):
File "<input>", line 1, in <module>
import im
File "im/__init__.py", line 2, in <module>
from im import (
TypeError: can't set attributes of built-in/extension type 'im.Image'
……我想我的做法是错误的;我应该尝试什么?
【问题讨论】:
标签: python python-c-api setattribute setattr pyobject