《扩展和嵌入python解释器》1.8 扩展函数的关键字参数

1.8 扩展函数的关键字参数

PyArg_ParseTupleAndKeywords()函数声明如下:

 

int PyArg_ParseTupleAndKeywords(PyObject *arg, PyObject *kwdict,
                                char *format, char *kwlist[], ...);

arg和format参数与PyArg_ParseTuple()函数完全相同。 kwdict参数是关键字字典作为从Python运行时接收到的第三个参数, kwlist参数是一个NULL结尾的用来标识参数的字符串; kwlist名称和format中类型信息匹配从左到右。函数PyArg_ParseTupleAndKeywords())成功返回true,否则返回false并产生合适的异常。

Note::当使用关键字参数时,嵌套的元组不能被解析。传入的关键字参数不能在kwlist里表示将产生TypeError异常。

下面是使用关键字的例子模块,基于Geoff Philbrick()的例子。

 

#include "Python.h"

static PyObject *
keywdarg_parrot(PyObject *self, PyObject *args, PyObject *keywds)
{  
    int voltage;
    char *state = "a stiff";
    char *action = "voom";
    char *type = "Norwegian Blue";

    static char *kwlist[] = {"voltage", "state", "action", "type", NULL};

    if (!PyArg_ParseTupleAndKeywords(args, keywds, "i|sss", kwlist, 
                                     &voltage, &state, &action, &type))
        return NULL; 
  
    printf("-- This parrot wouldn't %s if you put %i Volts through it./n", 
           action, voltage);
    printf("-- Lovely plumage, the %s -- It's %s!/n", type, state);

    Py_INCREF(Py_None);

    return Py_None;
}

static PyMethodDef keywdarg_methods[] = {
    /* The cast of the function is necessary since PyCFunction values
     * only take two PyObject* parameters, and keywdarg_parrot() takes
     * three.
     */
    {"parrot", (PyCFunction)keywdarg_parrot, METH_VARARGS | METH_KEYWORDS,
     "Print a lovely skit to standard output."},
    {NULL, NULL, 0, NULL}   /* sentinel */
};

 

void
initkeywdarg(void)
{
  /* Create the module and add the functions */
  Py_InitModule("keywdarg", keywdarg_methods);
}
 

你可能感兴趣的:(python,null,扩展,action,Parameters,methods)