boost :: python:如何覆盖静态属性?

问题描述 投票:1回答:2

我有一个基类和一个派生类,它们都有一个同名的静态方法。是否可以在保持名称相同的情况下公开两者?这样可以编译,但是在导入模块时会引发异常。

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

我有一个基类和一个派生类,它们都有一个同名的静态方法。是否可以在保持名称相同的情况下公开两者?这会编译,但是会抛出一个...

python c++ boost-python
2个回答
0
投票

[查看Boost Python如何公开静态属性以及它在Python中的行为看起来像是在Boost Python中的错误。


0
投票

问题是,当Boost.Python的元类尝试声明和设置Derived.say_hi时,它解析为Base.say_hi.__set__,因为它是从Base继承的现有类描述符。一种解决方案是将属性自己绑定到您的Derived类。例如:

© www.soinside.com 2019 - 2024. All rights reserved.