我有一个基类和一个派生类,它们都有一个同名的静态方法。是否可以在保持名称相同的情况下公开两者?这样可以编译,但是在导入模块时会引发异常。
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(); }
Hmm
我有一个基类和一个派生类,它们都有一个同名的静态方法。是否可以在保持名称相同的情况下公开两者?这会编译,但是会抛出一个...
[查看Boost Python
如何公开静态属性以及它在Python
中的行为看起来像是在Boost Python
中的错误。
问题是,当Boost.Python的元类尝试声明和设置Derived.say_hi
时,它解析为Base.say_hi.__set__
,因为它是从Base
继承的现有类描述符。一种解决方案是将属性自己绑定到您的Derived
类。例如: