1[section boost/python/class.hpp] 2[section Introduction] 3`<boost/python/class.hpp>` defines the interface through which users expose their C++ classes to Python. It declares the `class_` class template, which is parameterized on the class type being exposed. It also exposes the `init`, `optional` and `bases` utility class templates, which are used in conjunction with `class_`. 4 5`<boost/python/class_fwd.hpp>` contains a forward declaration of the `class_` class template. 6[endsect] 7[section Class template `class_<T, Bases, HeldType, NonCopyable>`] 8Creates a Python class associated with the C++ type passed as its first parameter. Although it has four template parameters, only the first one is required. The three optional arguments can actually be supplied *in any order*\ ; Boost.Python determines the role of the argument from its type. 9[table 10 [[Template Parameter][Requirements][Semantics][Default]] 11 [[`T`][A class type.][The class being wrapped][]] 12 [[Bases] 13 [A specialization of [link high_level_components.boost_python_class_hpp.class_template_bases_t1_t2_tn bases<...>] which specifies previously-exposed C++ base classes of `T`.] 14 [Registers `from_python` conversions from wrapped `T` instances to each of its exposed direct and indirect bases. For each polymorphic base `B`, registers conversions from indirectly-held wrapped `B` instances to `T`.][[link high_level_components.boost_python_class_hpp.class_template_bases_t1_t2_tn bases<>]]] 15 [[HeldType][Must be `T`, a class derived from `T`, or a [link concepts.dereferenceable.concept_requirements Dereferenceable] type for which `pointee<HeldType>::type` is `T` or a class derived from `T`.][Specifies the type that is actually embedded in a Python object wrapping a `T` instance when `T`\ 's constructor is called or when a `T` or `T*` is converted to Python without the use of [link function_invocation_and_creation.boost_python_ptr_hpp.functions ptr], `ref`, or [link concepts.callpolicies Call Policies] such as [link function_invocation_and_creation.models_of_callpolicies.boost_python_return_internal_ref.class_template_return_internal_r return_internal_reference]. More details below.][`T`]] 16 [[NonCopyable][If supplied, must be `boost::noncopyable`.][Suppresses automatic registration of `to_python` conversions which copy `T` instances. Required when `T` has no publicly-accessible copy constructor.][An unspecified type other than boost::noncopyable.]] 17] 18[section HeldType Semantics] 19 20# If HeldType is derived from `T`, its exposed constructor(s) must accept an initial `PyObject*` argument which refers back to the Python object that contains the HeldType instance, as shown in this example. This argument is not included in the [link high_level_components.boost_python_init_hpp.introduction.init_expressions init-expression] passed to [link high_level_components.boost_python_class_hpp.class_template_class_t_bases_hel.class_template_class_modifier_fu def(init_expr)], below, nor is it passed explicitly by users when Python instances of `T` are created. This idiom allows C++ virtual functions which will be overridden in Python to access the Python object so the Python method can be invoked. Boost.Python automatically registers additional converters which allow wrapped instances of `T` to be passed to wrapped C++ functions expecting HeldType arguments. 21# Because Boost.Python will always allow wrapped instances of `T` to be passed in place of HeldType arguments, specifying a smart pointer for HeldType allows users to pass Python `T` instances where a smart pointer-to-T is expected. Smart pointers such as `std::auto_ptr<>` or `boost::shared_ptr<>` which contain a nested type `element_type` designating the referent type are automatically supported; additional smart pointer types can be supported by specializing `pointee<HeldType>`. 22# As in case 1 above, when HeldType is a smart pointer to a class derived from `T`, the initial `PyObject*` argument must be supplied by all of HeldType's exposed constructors. 23# Except in cases 1 and 3, users may optionally specify that T itself gets initialized with a similar initial `PyObject*` argument by specializing [link utility_and_infrastructure.boost_python_has_back_reference_.class_template_has_back_referenc has_back_reference<T>]. 24 25[endsect] 26[section Class template `class_` synopsis] 27`` 28 namespace boost { namespace python 29 { 30 template <class T 31 , class Bases = bases<> 32 , class HeldType = T 33 , class NonCopyable = unspecified 34 > 35 class class_ : public object 36 { 37 // Constructors with default __init__ 38 class_(char const* name); 39 class_(char const* name, char const* docstring); 40 41 // Constructors, specifying non-default __init__ 42 template <class Init> 43 class_(char const* name, Init); 44 template <class Init> 45 class_(char const* name, char const* docstring, Init); 46 47 // Exposing additional __init__ functions 48 template <class Init> 49 class_& def(Init); 50 51 // defining methods 52 template <class F> 53 class_& def(char const* name, F f); 54 template <class Fn, class A1> 55 class_& def(char const* name, Fn fn, A1 const&); 56 template <class Fn, class A1, class A2> 57 class_& def(char const* name, Fn fn, A1 const&, A2 const&); 58 template <class Fn, class A1, class A2, class A3> 59 class_& def(char const* name, Fn fn, A1 const&, A2 const&, A3 const&); 60 61 // declaring method as static 62 class_& staticmethod(char const* name); 63 64 // exposing operators 65 template <unspecified> 66 class_& def(detail::operator_<unspecified>); 67 68 // Raw attribute modification 69 template <class U> 70 class_& setattr(char const* name, U const&); 71 72 // exposing data members 73 template <class D> 74 class_& def_readonly(char const* name, D T::*pm); 75 76 template <class D> 77 class_& def_readwrite(char const* name, D T::*pm); 78 79 // exposing static data members 80 template <class D> 81 class_& def_readonly(char const* name, D const& d); 82 template <class D> 83 class_& def_readwrite(char const* name, D& d); 84 85 // property creation 86 template <class Get> 87 void add_property(char const* name, Get const& fget, char const* doc=0); 88 template <class Get, class Set> 89 void add_property( 90 char const* name, Get const& fget, Set const& fset, char const* doc=0); 91 92 template <class Get> 93 void add_static_property(char const* name, Get const& fget); 94 template <class Get, class Set> 95 void add_static_property(char const* name, Get const& fget, Set const& fset); 96 97 // pickle support 98 template <typename PickleSuite> 99 self& def_pickle(PickleSuite const&); 100 self& enable_pickling(); 101 }; 102 }} 103`` 104[endsect] 105[section Class template `class_` constructors] 106`` 107 class_(char const* name); 108 class_(char const* name, char const* docstring); 109 template <class Init> 110 class_(char const* name, Init init_spec); 111 template <class Init> 112 class_(char const* name, char const* docstring, Init init_spec); 113`` 114 115[variablelist 116 [[Requires][name is an [link ntbs] which conforms to Python's [@http://www.python.org/doc/current/ref/identifiers.html identifier naming rules]. If docstring is supplied, it must be an [link ntbs]. If `init_spec` is supplied, it must be either the special enumeration constant `no_init` or an [link high_level_components.boost_python_init_hpp.introduction.init_expressions init-expression] compatible with `T`.]] 117 [[Effects][Constructs a `class_` object holding a Boost.Python extension class named name. The named attribute of the [link high_level_components.boost_python_scope_hpp.introduction current scope] is bound to the new extension class. 118 119* If supplied, the value of docstring is bound to the `__doc__` attribute of the extension class. 120* If `init_spec` is `no_init`, a special `__init__` function is generated which always raises a Python exception. Otherwise, `this->def(init_spec)` is called. 121* If `init_spec` is not supplied, `this->def(init<>())` is called.]] 122 [[Rationale][Allowing the user to specify constructor arguments in the `class_<>` constructor helps her to avoid the common run-time errors which result from invoking wrapped member functions without having exposed an `__init__` function which creates the requisite `T` instance. Types which are not default-constructible will cause a compile-time error unless `Init` is supplied. The user must always supply name as there is currently no portable method to derive the text of the class name from its type.]] 123] 124[endsect] 125[section Class template `class_` modifier functions] 126`` 127 template <class Init> 128 class_& def(Init init_expr); 129`` 130 131[variablelist 132 [[Requires][`init_expr` is the result of an [link high_level_components.boost_python_init_hpp.introduction.init_expressions init-expression] compatible with `T`.]] 133 [[Effects][For each [link high_level_components.boost_python_init_hpp.introduction.init_expressions valid prefix] `P` of `Init`, adds an `__init__(...)` function overload to the extension class accepting P as arguments. Each overload generated constructs an object of HeldType according to the semantics described above, using a copy of init_expr's call policies. If the longest [link high_level_components.boost_python_init_hpp.introduction.init_expressions valid prefix] of Init contains N types and init_expr holds M keywords, an initial sequence of the keywords are used for all but the first N - M arguments of each overload.]] 134 [[Returns][`*this`]] 135 [[Rationale][Allows users to easily expose a class' constructor to Python.]] 136] 137`` 138 template <class F> 139 class_& def(char const* name, Fn fn); 140 template <class Fn, class A1> 141 class_& def(char const* name, Fn fn, A1 const& a1); 142 template <class Fn, class A1, class A2> 143 class_& def(char const* name, Fn fn, A1 const& a1, A2 const& a2); 144 template <class Fn, class A1, class A2, class A3> 145 class_& def(char const* name, Fn fn, A1 const& a1, A2 const& a2, A3 const& a3); 146`` 147[variablelist 148 [[Requires][name is an [link ntbs] which conforms to Python's [@http://www.python.org/doc/current/ref/identifiers.html identifier naming rules]. 149 * If a1 is the result of an [link function_invocation_and_creation.boost_python_overloads_hpp.introduction.overload_dispatch_expressions overload-dispatch-expression], only the second form is allowed and fn must be a pointer to function or pointer to member function whose [link arity] is the same as A1's [link function_invocation_and_creation.boost_python_overloads_hpp.introduction.overload_dispatch_expressions maximum arity]. 150 151 [*Effects:] For each prefix `P` of `Fn`\ 's sequence of argument types, beginning with the one whose length is `A1`\ 's [link function_invocation_and_creation.boost_python_overloads_hpp.introduction.overload_dispatch_expressions minimum arity], adds a `name(...)` method overload to the extension class. Each overload generated invokes a1's call-expression with `P`, using a copy of a1's call policies. If the longest valid prefix of `A1` contains `N` types and a1 holds `M` keywords, an initial sequence of the keywords are used for all but the first `N - M` arguments of each overload. 152 153* Otherwise, a single method overload is built around fn, which must not be null: 154 155 * If fn is a function pointer, its first argument must be of the form U, U cv&, U cv*, or U cv* const&, where T* is convertible to U*, and a1-a3, if supplied, may be selected in any order from the table below. 156 * Otherwise, if fn is a member function pointer, its target must be T or one of its public base classes, and a1-a3, if supplied, may be selected in any order from the table below. 157 * Otherwise, Fn must be [derived from] [link object_wrappers.boost_python_object_hpp.class_object object], and a1-a2, if supplied, may be selcted in any order from the first two rows of the table below. To be useful, fn should be [@http://www.python.org/doc/current/lib/built-in-funcs.html#l2h-6 callable]. 158 [table 159 [[Mnemonic Name][Requirements/Type properties][Effects]] 160 [[docstring][Any [link ntbs]][Value will be bound to the __doc__ attribute of the resulting method overload. If an earlier overload supplied a docstring, two newline characters and the new docstring are appended to it.]] 161 [[policies][A model of [link concepts.callpolicies CallPolicies]][A copy will be used as the call policies of the resulting method overload.]] 162 [[keywords][The result of a [link function_invocation_and_creation.boost_python_args_hpp.introduction.keyword_expressions keyword-expression] specifying no more arguments than the [link arity] of fn.][A copy will be used as the call policies of the resulting method overload.]] 163 ] 164]] 165 [[Returns][`*this`]] 166] 167``class_& staticmethod(char const* name);`` 168[variablelist 169 [[Requires][name is an [link ntbs] which conforms to Python's [@http://www.python.org/doc/current/ref/identifiers.html identifier naming rules], and corresponds to a method whose overloads have all been defined.]] 170 [[Effects][Replaces the existing named attribute `x` with the result of invoking `staticmethod(x)` in Python. Specifies that the corresponding method is static and therefore no object instance will be passed to it. This is equivalent to the Python statement:]] 171] 172``setattr(self, name, staticmethod(getattr(self, name)))`` 173[variablelist 174 [[Note][Attempting to invoke def(name,...) after invoking staticmethod(name) will [link raise] a RuntimeError.]] 175 [[Returns][`*this`]] 176] 177`` 178template <unspecified> 179class_& def(detail::operator_<unspecified>); 180`` 181[variablelist 182 [[Effects][Adds a Python [@http://www.python.org/doc/ref/specialnames.html special method] as described [link high_level_components.boost_python_operators_hpp here].]] 183 [[Returns][`*this`]] 184] 185 186`` 187 template <class U> 188 class_& setattr(char const* name, U const& u); 189`` 190[variablelist 191 [[Requires][name is an [link ntbs] which conforms to Python's [@http://www.python.org/doc/current/ref/identifiers.html identifier naming rules].]] 192 [[Effects][Converts `u` to Python and adds it to the attribute dictionary of the extension class: 193 ``PyObject_SetAttrString(this->ptr(), name, object(u).ptr());``]] 194 [[Returns][`*this`]] 195] 196`` 197 template <class Get> 198 void add_property(char const* name, Get const& fget, char const* doc=0); 199 template <class Get, class Set> 200 void add_property( 201 char const* name, Get const& fget, Set const& fset, char const* doc=0); 202`` 203[variablelist 204 [[Requires][name is an [link ntbs] which conform to Python's [@http://www.python.org/doc/current/ref/identifiers.html identifier naming rules].]] 205 [[Effects][Creates a new Python [@http://www.python.org/2.2.2/descrintro.html#property property] class instance, passing `object(fget)` (and `object(fset)` in the second form) with an (optional) docstring `doc` to its constructor, then adds that property to the Python class object under construction with the given attribute name.]] 206 [[Returns][`*this`]] 207 [[Rationale][Allows users to easily expose functions that can be invoked from Python with attribute access syntax.]] 208] 209`` 210 template <class Get> 211 void add_static_property(char const* name, Get const& fget); 212 template <class Get, class Set> 213 void add_static_property(char const* name, Get const& fget, Set const& fset); 214`` 215[variablelist 216 [[Requires][name is an [link ntbs] which conforms to Python's [@http://www.python.org/doc/current/ref/identifiers.html identifier naming rules].]] 217 [[Effects][Creates a Boost.Python.StaticProperty object, passing `object(fget)` (and `object(fset)` in the second form) to its constructor, then adds that property to the Python class under construction with the given attribute name. StaticProperty is a special subclass of Python's property class which can be called without an initial self argument.]] 218 [[Returns][`*this`]] 219 [[Rationale][Allows users to easily expose functions that can be invoked from Python with static attribute access syntax.]] 220] 221`` 222 template <class D> 223 class_& def_readonly(char const* name, D T::*pm, char const* doc=0); 224 template <class D> 225 class_& def_readonly(char const* name, D const& d); 226`` 227[variablelist 228 [[Requires][name is an [link ntbs] which conforms to Python's [@http://www.python.org/doc/current/ref/identifiers.html identifier naming rules]. `doc` is also an [link ntbs].]] 229 [[Effects][``this->add_property(name, make_getter(pm), doc);`` and ``this->add_static_property(name, make_getter(d));`` respectively.]] 230 [[Returns][`*this`]] 231 [[Rationale][Allows users to easily expose a class' data member or free variable such that it can be inspected from Python with a natural syntax.]] 232] 233`` 234 template <class D> 235 class_& def_readwrite(char const* name, D T::*pm, char const* doc=0); 236 template <class D> 237 class_& def_readwrite(char const* name, D& d); 238`` 239[variablelist 240[[Effects][``this->add_property(name, make_getter(pm), make_setter(pm), doc);`` and ``this->add_static_property(name, make_getter(d), make_setter(d));`` respectively.]] 241[[Returns][`*this`]] 242[[Rationale][Allows users to easily expose a class' data or free variable member such that it can be inspected and set from Python with a natural syntax.]] 243] 244`` 245 template <typename PickleSuite> 246 class_& def_pickle(PickleSuite const&); 247`` 248[variablelist 249[[Requires][PickleSuite must be publically derived from [link topics.pickle_support.the_pickle_interface pickle_suite].]] 250[[Effects][Defines a legal combination of the special attributes and methods: __getinitargs__, __getstate__, __setstate__, __getstate_manages_dict__, __safe_for_unpickling__, __reduce__]] 251[[Returns][`*this`]] 252[[Rationale][Provides an [link topics.pickle_support.the_pickle_interface easy to use high-level interface] for establishing complete [link topics.pickle_support.the_pickle_interface pickle support] for the wrapped class. The user is protected by compile-time consistency checks.]] 253] 254``class_& enable_pickling();`` 255[variablelist 256[[Effects][Defines the __reduce__ method and the __safe_for_unpickling__ attribute.]] 257[[Returns][`*this`]] 258[[Rationale][Light-weight alternative to def_pickle(). Enables implementation of pickle support from Python.]] 259] 260[endsect] 261[endsect] 262[section Class template bases<T1, T2, ...TN>] 263An MPL sequence which can be used in class_<...> instantiations indicate a list of base classes. 264[section Class template bases synopsis] 265`` 266namespace boost { namespace python 267{ 268 template <T1 = unspecified,...Tn = unspecified> 269 struct bases 270 {}; 271}} 272`` 273[endsect] 274[endsect] 275[section Examples] 276Given a C++ class declaration: 277`` 278class Foo : public Bar, public Baz 279{ 280 public: 281 Foo(int x, char const* y); 282 Foo(double); 283 284 std::string const& name() { return m_name; } 285 void name(char const*); 286 287 double value; // public data 288 private: 289 ... 290}; 291`` 292A corresponding Boost.Python extension class can be created with: 293`` 294using namespace boost::python; 295 296class_<Foo,bases<Bar,Baz> >("Foo", 297 "This is Foo's docstring." 298 "It describes our Foo extension class", 299 300 init<int,char const*>(args("x","y"), "__init__ docstring") 301 ) 302 .def(init<double>()) 303 .def("get_name", &Foo::get_name, return_internal_reference<>()) 304 .def("set_name", &Foo::set_name) 305 .def_readwrite("value", &Foo::value); 306`` 307[endsect] 308[endsect] 309