【问题标题】:How to provide default enum value with pybind11?如何使用 pybind11 提供默认枚举值?
【发布时间】:2019-12-08 19:46:42
【问题描述】:

我想让函数接受枚举默认参数。

但我找不到在 PyBind11 enum example 和文档中提供枚举默认值的正确方法,例如:

struct Pet
{
    enum Kind
    {
        Dog = 0,
        Cat
    };

    Pet(const std::string &name) : name(name)
    {
    }

    void setName(const std::string &name_)
    {
        name = name_;
    }

    const std::string &getName() const
    {
        return name;
    }

    Kind test(Kind kind = Dog)
    {
        if(kind == Dog)
           std::cout << "Dog" << std::endl;

        if(kind == Cat)
           std::cout << "Cat" << std::endl;

        return kind;
    }

    std::string name;
};

PYBIND11_MODULE(pet,m)
{
    py::class_<Pet> pet(m, "Pet");
    pet.def(py::init<const std::string &>())
       .def("setName", &Pet::setName)
       .def("getName", &Pet::getName)
       .def("test", &Pet::test, py::arg("kind") = Pet::Kind::Dog)
       .def("__repr__", [](const Pet &a) { return "<example.Pet named '" + a.name + "'>"; }
    );

    py::enum_<Pet::Kind>(pet, "Kind")
        .value("Dog", Pet::Kind::Dog)
        .value("Cat", Pet::Kind::Cat)
        .export_values();

但它不起作用:

py::arg("kind") = Pet::Kind::Dog 

当我在 Python 中运行它时,我遇到了错误。

from pet import Pet as p
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: arg(): could not convert default argument into a Python object (type not registered yet?). Compile in debug mode for more information.

当我尝试用字符串值初始化它时出现错误,即“Dog”或为 1。

【问题讨论】:

    标签: python c++ enums default pybind11


    【解决方案1】:

    这是一个简单的排序问题:在加载时,模块定义中的语句被执行以创建 Python 类、函数等。因此,首先定义 Kind(即在 Python 端)以允许解释器在稍后定义 test 时在设置默认值时找到它。即,使用此顺序:

    PYBIND11_MODULE(pet,m)
    {
        py::class_<Pet> pet(m, "Pet");
    
        py::enum_<Pet::Kind>(pet, "Kind")
            .value("Dog", Pet::Kind::Dog)
            .value("Cat", Pet::Kind::Cat)
            .export_values();
    
        pet.def(py::init<const std::string &>())
           .def("setName", &Pet::setName)
           .def("getName", &Pet::getName)
           .def("test", &Pet::test, py::arg("kind") = Pet::Kind::Dog)
           .def("__repr__", [](const Pet &a) { return "<example.Pet named '" + a.name + "'>"; }
        );
    
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-10-27
      • 1970-01-01
      • 2011-10-14
      • 1970-01-01
      • 1970-01-01
      • 2013-07-25
      • 1970-01-01
      相关资源
      最近更新 更多