{site_name}

{site_name}

🌜 搜索

Python中的METH_O和METH_NOARGS是用于定义C语言实现的Python对象方法的宏

Python 𝄐 0
pythonmethod
Python中的METH_O和METH_NOARGS是用于定义C语言实现的Python对象方法的宏。这些宏可以简化Python对象方法的定义,并提高了Python解释器的性能。

METH_NOARGS宏用于定义没有参数的Python对象方法,其声明如下:

c
#define METH_NOARGS (METH_VARARGS | METH_KEYWORDS)


METH_O宏用于定义一个接受单个Python对象作为参数的Python对象方法,其声明如下:

c
#define METH_O (METH_VARARGS | METH_KEYWORDS)


下面是一个使用METH_NOARGS的例子,定义了一个只打印一行字符串的Python对象方法:

c
static PyObject *
myobject_print(PyObject *self, PyObject *args, PyObject *kwargs)
{
static char *kwlist[] = {NULL};

if (!PyArg_ParseTupleAndKeywords(args, kwargs, "", kwlist))
return NULL;

printf("Hello from myobject!\n");

Py_RETURN_NONE;
}

static PyMethodDef myobject_methods[] = {
{"print", (PyCFunction) myobject_print, METH_NOARGS,
"Print a greeting from myobject"},
{NULL, NULL, 0, NULL} /* Sentinel */
};

static PyTypeObject MyObjectType = {
PyVarObject_HEAD_INIT(NULL, 0)
.tp_name = "myobject.MyObject",
.tp_doc = "MyObject objects",
.tp_basicsize = sizeof(MyObject),
.tp_itemsize = 0,
.tp_flags = Py_TPFLAGS_DEFAULT,
.tp_new = myobject_new,
.tp_init = (initproc) myobject_init,
.tp_dealloc = (destructor) myobject_dealloc,
.tp_methods = myobject_methods,
};


下面是一个使用METH_O的例子,定义了一个将Python字符串转换为大写字母的Python对象方法:

c
static PyObject *
myobject_upper(PyObject *self, PyObject *args, PyObject *kwargs)
{
PyObject *obj;

static char *kwlist[] = {"obj", NULL};

if (!PyArg_ParseTupleAndKeywords(args, kwargs, "O", kwlist, &obj))
return NULL;

if (!PyUnicode_Check(obj)) {
PyErr_SetString(PyExc_TypeError, "must be a string");
return NULL;
}

obj = PyUnicode_FromObject(obj);
if (!obj)
return NULL;

obj = PyUnicode_AsASCIIString(obj);
if (!obj)
return NULL;

obj = PyUnicode_FromStringAndSize(
PyBytes_AS_STRING(obj), PyBytes_GET_SIZE(obj));
if (!obj)
return NULL;

obj = PyUnicode_AsUTF8String(obj);
if (!obj)
return NULL;

obj = PyUnicode_FromEncodedObject(obj, "utf-8", "strict");
if (!obj)
return NULL;

obj = PyUnicode_AsUpper(obj);
if (!obj)
return NULL;

return obj;
}

static PyMethodDef myobject_methods[] = {
{"upper", (PyCFunction) myobject_upper, METH_O,
"Return a copy of the string converted to uppercase."},
{NULL, NULL, 0, NULL} /* Sentinel */
};

static PyTypeObject MyObjectType = {
PyVarObject_HEAD_INIT(NULL, 0)
.tp_name = "myobject.MyObject",
.tp_doc = "MyObject objects",
.tp_basicsize = sizeof(MyObject),
.tp_itemsize = 0,
.tp_flags = Py_TPFLAGS_DEFAULT,
.tp_new = myobject_new,
.tp_init = (initproc) myobject_init,
.tp_dealloc = (destructor) myobject_dealloc,
.tp_methods = myobject_methods,
};