Boost C++ Libraries Home Libraries People FAQ More

PrevUpHomeNext

Example

The following example shows how scope setting can be used to define nested classes.

C++ Module definition:

#include <boost/python/module.hpp>
#include <boost/python/class.hpp>
#include <boost/python/scope.hpp>
using namespace boost::python;

struct X
{
  void f() {}

  struct Y { int g() { return 42; } };
};

BOOST_PYTHON_MODULE(nested)
{
   // add some constants to the current (module) scope
   scope().attr("yes") = 1;
   scope().attr("no") = 0;

   // Change the current scope 
   scope outer
       = class_<X>("X")
            .def("f", &X::f)
            ;

   // Define a class Y in the current scope, X
   class_<X::Y>("Y")
      .def("g", &X::Y::g)
      ;
}

Interactive Python:

>>> import nested
>>> nested.yes
1
>>> y = nested.X.Y()
>>> y.g()
42

PrevUpHomeNext