python dict函数用法_如何将python中的dict作为参数传入c函数中用c做相关的处理?...
展開全部
#先上代碼再解釋
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 */
};
PyObject * initkeywdarg(void)
{
/* Create the module and add the functions */
return Py_InitModule("keywdarg", keywdarg_methods);
}
這是一個函數(keywdarg_parrot)即使用了元組參數,也32313133353236313431303231363533e4b893e5b19e31333335333064使用了字典參數的例子。例子出自Python2.7.2的文檔。具體在:
Python v2.7.2 documentation ?Extending and Embedding the Python
Interpreter
這個頁面下。文檔里面有一些關于C/C++與Python交互的介紹和例子,還是比較詳細的。傳遞字典參量要注意,{"parrot", (PyCFunction)keywdarg_parrot, METH_VARARGS | METH_KEYWORDS,
"Print a lovely skit to standard output."},
這里的METH_VARARGS | METH_KEYWORDS,與普通的不同。解析用:PyArg_ParseTupleAndKeywords(args, keywds, "i|sss", kwlist,
&voltage, &state, &action, &type)
其中的四個變量要提前聲明好,這里分別是int,str,str,str類型的。int對應的是args接受到的值。string的都是keywds里面的,它們都是有初始值的。kwlist是變量的名字,就是在python里調用的時候使用的keyword名稱。照著例子的模式可以改成其它的,能用的。具體是怎么工作的,其實我也太明白。
Python代碼是這樣的調用的時候:print keywdarg.parrot(10,"LHJ",'HKJ','ER')
print keywdarg.parrot(10,"LHJ",'HKJ')
print keywdarg.parrot(10,"LHJ",type='KJ')
輸出分別是:
-- This parrot wouldn't HKJ if you put 10 Volts through it.
-- Lovely plumage, the ER -- It's LHJ!
None
-- This parrot wouldn't HKJ if you put 10 Volts through it.
-- Lovely plumage, the Norwegian Blue -- It's LHJ!
None
-- This parrot wouldn't voom if you put 10 Volts through it.
-- Lovely plumage, the KJ -- It's LHJ!
None
第二次調用省略掉了變量,也能正常執行。第三次調用,變量type本來是第四位的,現在變成了keyword并寫在了第三位,是python代碼里調用的常見形式:keyword不講順序,省略掉的keyword使用了默認值。
就這些了,其它的你再看一下Python的文檔吧。
總結
以上是生活随笔為你收集整理的python dict函数用法_如何将python中的dict作为参数传入c函数中用c做相关的处理?...的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 基金净值已经翻倍还可以买入 需要分析不
- 下一篇: python安装mysqlclient报