【发布时间】:2012-04-27 01:03:34
【问题描述】:
使用 Python C-API 创建类属性(如here 和here)的最佳方法是什么?静态属性也适用于我的情况。
跟进:
我尝试执行 yak 的建议。我在其tp_descr_get 和tp_descr_set 插槽中定义了一个类P 和get 和set 函数。然后我将P 的实例添加到X 类的类型对象字典中,键为p。那么
x1 = X()
x2 = X()
x1.p = 10
print x1.p
print x2.p
print X.p
x2.p = 11
print x1.p
print x2.p
print X.p
有效(前 10 打印 3 次,然后 11 打印 3 次),但是
X.p = 12
失败并显示错误消息
TypeError: can't set attributes of built-in/extension type 'X'
我该如何解决这个问题?
跟进2:
如果我使用PyMem_Malloc 分配类型对象并设置Py_TPFLAGS_HEAPTYPE 标志,那么一切正常;我可以做到X.p = 12 得到预期的结果。
如果我将类型对象保存在静态变量中并设置Py_TPFLAGS_HEAPTYPE 标志,事情也会起作用,但这显然不是一个好主意。 (但是为什么类型对象是在静态内存还是动态内存中很重要?我从不让它的引用计数下降到 0。)
只能在动态类型上设置属性的限制看起来很奇怪。这背后的原理是什么?
跟进3:
不,它不起作用。如果我将类型 X 设为动态,则 X.p = 12 不会将属性 X.p 设置为十二;它实际上将对象12 绑定到名称X.p。也就是说,事后X.p不是整数值属性,而是整数。
跟进4:
这是扩展的 C++ 代码:
#include <python.h>
#include <exception>
class ErrorAlreadySet : public std::exception {};
// P type ------------------------------------------------------------------
struct P : PyObject
{
PyObject* value;
};
PyObject* P_get(P* self, PyObject* /*obj*/, PyObject* /*type*/)
{
Py_XINCREF(self->value);
return self->value;
}
int P_set(P* self, PyObject* /*obj*/, PyObject* value)
{
Py_XDECREF(self->value);
self->value = value;
Py_XINCREF(self->value);
return 0;
}
struct P_Type : PyTypeObject
{
P_Type()
{
memset(this, 0, sizeof(*this));
ob_refcnt = 1;
tp_name = "P";
tp_basicsize = sizeof(P);
tp_descr_get = (descrgetfunc)P_get;
tp_descr_set = (descrsetfunc)P_set;
tp_flags = Py_TPFLAGS_DEFAULT;
if(PyType_Ready(this)) throw ErrorAlreadySet();
}
};
PyTypeObject* P_type()
{
static P_Type typeObj;
return &typeObj;
}
// P singleton instance ----------------------------------------------------
P* createP()
{
P* p_ = PyObject_New(P, P_type());
p_->value = Py_None;
Py_INCREF(p_->value);
return p_;
}
P* p()
{
static P* p_ = createP();
Py_INCREF(p_);
return p_;
}
PyObject* p_value()
{
PyObject* p_ = p();
PyObject* value = p()->value;
Py_DECREF(p_);
Py_INCREF(value);
return value;
}
// X type ------------------------------------------------------------------
struct X : PyObject {};
void X_dealloc(PyObject* self)
{
self->ob_type->tp_free(self);
}
struct X_Type : PyTypeObject
{
X_Type()
{
memset(this, 0, sizeof(*this));
ob_refcnt = 1;
tp_name = "M.X";
tp_basicsize = sizeof(X);
tp_dealloc = (destructor)X_dealloc;
tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HEAPTYPE;
tp_dict = PyDict_New();
PyObject* key = PyString_FromString("p");
PyObject* value = p();
PyDict_SetItem(tp_dict, key, value);
Py_DECREF(key);
Py_DECREF(value);
if(PyType_Ready(this)) throw ErrorAlreadySet();
}
void* operator new(size_t n) { return PyMem_Malloc(n); }
void operator delete(void* p) { PyMem_Free(p); }
};
PyTypeObject* X_type()
{
static PyTypeObject* typeObj = new X_Type;
return typeObj;
}
// module M ----------------------------------------------------------------
PyMethodDef methods[] =
{
{"p_value", (PyCFunction)p_value, METH_NOARGS, 0},
{0, 0, 0, 0}
};
PyMODINIT_FUNC
initM(void)
{
try {
PyObject* m = Py_InitModule3("M", methods, 0);
if(!m) return;
PyModule_AddObject(m, "X", (PyObject*)X_type());
}
catch(const ErrorAlreadySet&) {}
}
这段代码定义了一个模块M,其类为X,其类属性为p,如前所述。我还添加了一个函数p_value(),让您可以直接检查实现该属性的对象。
这是我用来测试扩展的脚本:
from M import X, p_value
x1 = X()
x2 = X()
x1.p = 1
print x1.p
print x2.p
print X.p
print p_value()
print
x2.p = 2
print x1.p
print x2.p
print X.p
print p_value()
print
X.p = 3
print x1.p
print x2.p
print X.p
print p_value() # prints 2
print
x1.p = 4 # AttributeError: 'M.X' object attribute 'p' is read-only
【问题讨论】:
-
查看这个以获得 Guido 的解释:mail.python.org/pipermail/python-dev/2008-February/077167.html
标签: python python-c-api