我有一个C类,我正在使用boost ::
python构建一个
python模块.我有一些函数,我想采取关键字参数.我已经设置了包装函数来传递给raw_arguments,并且工作正常,但我想构建一些函数参数的错误检查.有没有标准的方法来做到这一点?
我在C中的函数原型看起来有点像这样:
double MyClass::myFunction(int a,int b,int c);
第三个参数是可选的,默认值为0(到目前为止,我已经使用宏在boost :: python中实现了这个).在python中,我希望能够实现以下行为:
MyClass.my_function(1) # Raises exception MyClass.my_function(2,3) # So that a = 2,b = 3 and c defaults to 0 MyClass.my_function(2,3,1) # As above,but Now c = 1 MyClass.my_function(2,1,3) # Raises exception MyClass.my_function(3,c = 2) # So a = 3,b = 1 and c = 2 MyClass.my_function(a = 2,b = 2,c = 3) # Speaks for itself MyClass.my_function(b = 2,c = 1) # Raises exception
boost :: python或raw_function包装器中有什么东西可以促进这一点,或者我是否需要编写代码来自行检查所有这些?如果我确实需要,我该如何提出异常?有这样做的标准方法吗?
解决方法
boost/python/args.hpp文件提供了一系列用于指定参数关键字的类.特别是,Boost.Python提供了
arg类型,表示潜在的关键字参数.它会重载逗号运算符,以允许更自然地定义参数列表.
在myClass上公开myFunction作为my_function,其中a,b和c是关键字参数,c的默认值为0,可以写成如下:
BOOST_PYTHON_MODULE(example)
{
namespace python = boost::python;
python::class_<MyClass>("MyClass")
.def("my_function",&MyClass::myFunction,(python::arg("a"),"b",python::arg("c")=0))
;
}
这是一个完整的例子:
#include <boost/python.hpp>
class MyClass
{
public:
double myFunction(int a,int c)
{
return a + b + c;
}
};
BOOST_PYTHON_MODULE(example)
{
namespace python = boost::python;
python::class_<MyClass>("MyClass")
.def("my_function",python::arg("c")=0))
;
}
互动用法:
>>> import example
>>> my_class = example.MyClass()
>>> my_class.my_function(1)
Traceback (most recent call last):
File "<stdin>",line 1,in <module>
Boost.Python.ArgumentError: Python argument types in
MyClass.my_function(MyClass,int)
did not match C++ signature:
my_function(MyClass {lvalue},int a,int c=0)
>>> assert(5 == my_class.my_function(2,3))
>>> assert(6 == my_class.my_function(2,1))
>>> my_class.my_function(2,3)
Traceback (most recent call last):
File "<stdin>",int,int c=0)
>>> assert(6 == my_class.my_function(3,c=2))
>>> assert(7 == my_class.my_function(a=2,b=2,c=3))
>>> my_class.my_function(b=2,c=1)
Traceback (most recent call last):
File "<stdin>",in <module>
Boost.Python.ArgumentError: Python argument types in
MyClass.my_function(MyClass)
did not match C++ signature:
my_function(MyClass {lvalue},int c=0)