【问题标题】:how to pass arguments to a python function that has variant argument?如何将参数传递给具有变体参数的python函数?
【发布时间】:2020-03-06 12:55:30
【问题描述】:

我使用 boost::python 在 C++ 端回调一个 python 函数,python 函数可能有变体参数,它看起来像:

foo(int) ,
foo(int ,double),
foo(string , othertype,...) , 

在我的 C++ 程序中,我将 foo 作为 boost::python::object 发送,

void Call(object foo)
{
//check each argument and assign value for example
int arg1=2;
string arg2="hehe";
.....
//then send above arguments to foo , but how to send?
foo(??);
}

现在我可以获取每个参数名称并相应地给出值,但我的问题是:如何将值传递给 foo ?

我使用 boost::python::list 或元组来收集数据,但不起作用,参数错误。 任何人都可以帮助我吗?非常感谢。

【问题讨论】:

  • 我不确定你所说的具有变体参数的 Python 函数是什么意思。据我所知,C++ 风格的函数重载在 Python 中几乎不是什么东西,除了 PEP443 的实现:python.org/dev/peps/pep-0443

标签: python c++ boost


【解决方案1】:
def myFun(arg1, **kwargs):  
    for key, value in kwargs.items(): 
        print ("%s == %s" %(key, value)) 

# Driver code 
myFun("Hi", first ='Geeks', mid ='for', last='Geeks') 

您可以使用 **args: 因此您可以将多个不同类型的参数作为 dict 类型传递

您可以查看此链接了解更多信息:https://www.geeksforgeeks.org/args-kwargs-python/

【讨论】:

  • 感谢您的评论,但我认为您误解了我的意图,我在 C++ 程序中调用 foo , foo 函数几乎固定为位置参数,所以我的问题是如何在 C++ 中打包参数并传递它们到foo
猜你喜欢
  • 2014-10-31
  • 1970-01-01
  • 2019-12-19
  • 2017-06-22
  • 2015-01-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多