【发布时间】:2020-01-21 21:36:46
【问题描述】:
我有一个基类和一个派生类,它们都有一个同名的静态方法。是否可以在保持名称相同的同时公开它们?这会编译,但在导入模块时会引发异常。
struct Base
{
static std::string say_hi() { return "Hi"; }
};
struct Derived : public Base
{
static std::string say_hi() { return "Hello"; }
};
BOOST_PYTHON_MODULE(HelloBoostPython)
{
namespace py = boost::python;
py::class_<Base>("Base").add_static_property("say_hi", &Base::say_hi);
py::class_<Derived, py::bases<Base>>("Derived").add_static_property("say_hi", &Derived::say_hi);
}
导入时:
>>> import HelloBoostPython
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
SystemError: initialization of HelloBoostPython raised unreported exception
将最后一行更改为不同的名称可以,但我宁愿覆盖基类的属性:
py::class_<Derived, py::bases<Base>>("Derived").add_static_property("say_hello", &Derived::say_hi);
这可行,但我得到的是类方法而不是属性:
BOOST_PYTHON_MODULE(HelloBoostPython)
{
namespace py = boost::python;
py::object base = py::class_<Base>("Base");
base.attr("say_hi") = Base::say_hi;
py::object derived = py::class_<Derived, py::bases<Base>>("Derived");
derived.attr("say_hi") = Derived::say_hi;
}
这将为我提供属性,但如果静态方法不是常量,则在一般情况下不起作用:
BOOST_PYTHON_MODULE(HelloBoostPython)
{
namespace py = boost::python;
py::object base = py::class_<Base>("Base");
base.attr("say_hi") = Base::say_hi();
py::object derived = py::class_<Derived, py::bases<Base>>("Derived");
derived.attr("say_hi") = Derived::say_hi();
}
嗯
【问题讨论】:
-
什么是“未报告的异常”? (例如,您可以使用
PyErr_WriteUnraisable。)
标签: python c++ boost-python