【问题标题】:Named parameters with Python C API?使用 Python C API 命名参数?
【发布时间】:2010-12-25 10:54:36
【问题描述】:

如何使用 Python C API 模拟以下 Python 函数?

def foo(bar, baz="something or other"):
    print bar, baz

(即,可以通过以下方式调用它:

>>> foo("hello")
hello something or other
>>> foo("hello", baz="world!")
hello world!
>>> foo("hello", "world!")
hello, world!

)

【问题讨论】:

    标签: python c python-c-api named-parameters


    【解决方案1】:

    请参阅the docs:您想使用PyArg_ParseTupleAndKeywords,记录在我提供的 URL 中。

    例如:

    def foo(bar, baz="something or other"):
        print bar, baz
    

    变成(大概——还没有测试过!):

    #include "Python.h"
    
    static PyObject *
    themodule_foo(PyObject *self, PyObject *args, PyObject *keywds)
    {
        char *bar;
        char *baz = "something or other";
    
        static char *kwlist[] = {"bar", "baz", NULL};
    
        if (!PyArg_ParseTupleAndKeywords(args, keywds, "s|s", kwlist,
                                         &bar, &baz))
            return NULL;
    
        printf("%s %s\n", bar, baz);
    
        Py_INCREF(Py_None);
        return Py_None;
    }
    
    static PyMethodDef themodule_methods[] = {
        {"foo", (PyCFunction)themodule_foo, METH_VARARGS | METH_KEYWORDS,
         "Print some greeting to standard output."},
        {NULL, NULL, 0, NULL}   /* sentinel */
    };
    
    void
    initthemodule(void)
    {
      Py_InitModule("themodule", themodule_methods);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-01-25
      • 1970-01-01
      • 2011-03-09
      • 1970-01-01
      • 1970-01-01
      • 2018-06-11
      • 2011-12-18
      • 1970-01-01
      相关资源
      最近更新 更多