概述
AttributeError是尝试在没有第一个设置范围的情况下创建Python扩展类型的结果. boost::python::enum_构造函数指出:
Constructs an enum_ object holding a Python extension type derived from int which is named name. The named attribute of the current scope is bound to the new extension type.
嵌入Python时,要使用自定义Python模块,通常最容易使用PyImport_AppendInittab,然后按名称导入该模块.
PyImport_AppendInittab("example", &initexample);
...
boost::python::object example = boost::python::import("example");
这是一个完整的示例,显示了通过Boost.Python公开的两个枚举.一个包含在由main导入的单独模块(示例)中,另一个则直接在main中公开.
#include
#include
/// @brief Mockup class with a nested enum.
struct TestClass
{
/// @brief Mocked enum.
enum Motion
{
walk,
bike
};
// @brief Mocked enum.
enum Color
{
red,
blue
};
};
/// @brief Python example module.
BOOST_PYTHON_MODULE(example)
{
namespace python = boost::python;
python::enum_<:motion>("Motion")
.value("walk", TestClass::walk)
.value("bike", TestClass::bike)
;
}
int main()
{
PyImport_AppendInittab("example", &initexample); // Add example to built-in.
Py_Initialize(); // Start interpreter.
// Create the __main__ module.
namespace python = boost::python;
try
{
python::object main = python::import("__main__");
python::object main_namespace = main.attr("__dict__");
python::scope scope(main); // Force main scope
// Expose TestClass::Color as Color
python::enum_<:color>("Color")
.value("red", TestClass::red)
.value("blue", TestClass::blue)
;
// Print values of Color enumeration.
python::exec(
"print Color.values",
main_namespace, main_namespace);
// Get a handle to the Color enumeration.
python::object color = main_namespace["Color"];
python::object blue = color.attr("blue");
if (TestClass::blue == python::extract<:color>(blue))
std::cout << "blue enum values matched." << std::endl;
// Import example module into main namespace.
main_namespace["example"] = python::import("example");
// Print the values of the Motion enumeration.
python::exec(
"print example.Motion.values",
main_namespace, main_namespace);
// Check if the Python enums match the C++ enum values.
if (TestClass::bike == python::extract<:motion>(
main_namespace["example"].attr("Motion").attr("bike")))
std::cout << "bike enum values matched." << std::endl;
}
catch (const python::error_already_set&)
{
PyErr_Print();
}
}
输出:
{0: __main__.Color.red, 1: __main__.Color.blue}
blue enum values matched.
{0: example.Motion.walk, 1: example.Motion.bike}
bike enum values matched.
最后
以上就是笨笨刺猬为你收集整理的python中封装一个枚举_使用Boost-Python包装枚举的全部内容,希望文章能够帮你解决python中封装一个枚举_使用Boost-Python包装枚举所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
发表评论 取消回复