class.qbk 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308
  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. `<boost/python/class_fwd.hpp>` contains a forward declaration of the `class_` class template.
  5. [endsect]
  6. [section Class template `class_<T, Bases, HeldType, NonCopyable>`]
  7. Creates 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.
  8. [table
  9. [[Template Parameter][Requirements][Semantics][Default]]
  10. [[`T`][A class type.][The class being wrapped][]]
  11. [[Bases]
  12. [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`.]
  13. [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<>]]]
  14. [[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`]]
  15. [[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.]]
  16. ]
  17. [section HeldType Semantics]
  18. # 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.
  19. # 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>`.
  20. # 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.
  21. # 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>].
  22. [endsect]
  23. [section Class template `class_` synopsis]
  24. ``
  25. namespace boost { namespace python
  26. {
  27. template <class T
  28. , class Bases = bases<>
  29. , class HeldType = T
  30. , class NonCopyable = unspecified
  31. >
  32. class class_ : public object
  33. {
  34. // Constructors with default __init__
  35. class_(char const* name);
  36. class_(char const* name, char const* docstring);
  37. // Constructors, specifying non-default __init__
  38. template <class Init>
  39. class_(char const* name, Init);
  40. template <class Init>
  41. class_(char const* name, char const* docstring, Init);
  42. // Exposing additional __init__ functions
  43. template <class Init>
  44. class_& def(Init);
  45. // defining methods
  46. template <class F>
  47. class_& def(char const* name, F f);
  48. template <class Fn, class A1>
  49. class_& def(char const* name, Fn fn, A1 const&);
  50. template <class Fn, class A1, class A2>
  51. class_& def(char const* name, Fn fn, A1 const&, A2 const&);
  52. template <class Fn, class A1, class A2, class A3>
  53. class_& def(char const* name, Fn fn, A1 const&, A2 const&, A3 const&);
  54. // declaring method as static
  55. class_& staticmethod(char const* name);
  56. // exposing operators
  57. template <unspecified>
  58. class_& def(detail::operator_<unspecified>);
  59. // Raw attribute modification
  60. template <class U>
  61. class_& setattr(char const* name, U const&);
  62. // exposing data members
  63. template <class D>
  64. class_& def_readonly(char const* name, D T::*pm);
  65. template <class D>
  66. class_& def_readwrite(char const* name, D T::*pm);
  67. // exposing static data members
  68. template <class D>
  69. class_& def_readonly(char const* name, D const& d);
  70. template <class D>
  71. class_& def_readwrite(char const* name, D& d);
  72. // property creation
  73. template <class Get>
  74. void add_property(char const* name, Get const& fget, char const* doc=0);
  75. template <class Get, class Set>
  76. void add_property(
  77. char const* name, Get const& fget, Set const& fset, char const* doc=0);
  78. template <class Get>
  79. void add_static_property(char const* name, Get const& fget);
  80. template <class Get, class Set>
  81. void add_static_property(char const* name, Get const& fget, Set const& fset);
  82. // pickle support
  83. template <typename PickleSuite>
  84. self& def_pickle(PickleSuite const&);
  85. self& enable_pickling();
  86. };
  87. }}
  88. ``
  89. [endsect]
  90. [section Class template `class_` constructors]
  91. ``
  92. class_(char const* name);
  93. class_(char const* name, char const* docstring);
  94. template <class Init>
  95. class_(char const* name, Init init_spec);
  96. template <class Init>
  97. class_(char const* name, char const* docstring, Init init_spec);
  98. ``
  99. [variablelist
  100. [[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`.]]
  101. [[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.
  102. * If supplied, the value of docstring is bound to the `__doc__` attribute of the extension class.
  103. * 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.
  104. * If `init_spec` is not supplied, `this->def(init<>())` is called.]]
  105. [[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.]]
  106. ]
  107. [endsect]
  108. [section Class template `class_` modifier functions]
  109. ``
  110. template <class Init>
  111. class_& def(Init init_expr);
  112. ``
  113. [variablelist
  114. [[Requires][`init_expr` is the result of an [link high_level_components.boost_python_init_hpp.introduction.init_expressions init-expression] compatible with `T`.]]
  115. [[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.]]
  116. [[Returns][`*this`]]
  117. [[Rationale][Allows users to easily expose a class' constructor to Python.]]
  118. ]
  119. ``
  120. template <class F>
  121. class_& def(char const* name, Fn fn);
  122. template <class Fn, class A1>
  123. class_& def(char const* name, Fn fn, A1 const& a1);
  124. template <class Fn, class A1, class A2>
  125. class_& def(char const* name, Fn fn, A1 const& a1, A2 const& a2);
  126. template <class Fn, class A1, class A2, class A3>
  127. class_& def(char const* name, Fn fn, A1 const& a1, A2 const& a2, A3 const& a3);
  128. ``
  129. [variablelist
  130. [[Requires][name is an [link ntbs] which conforms to Python's [@http://www.python.org/doc/current/ref/identifiers.html identifier naming rules].
  131. * 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].
  132. [*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.
  133. * Otherwise, a single method overload is built around fn, which must not be null:
  134. * 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.
  135. * 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.
  136. * 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].
  137. [table
  138. [[Mnemonic Name][Requirements/Type properties][Effects]]
  139. [[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.]]
  140. [[policies][A model of [link concepts.callpolicies CallPolicies]][A copy will be used as the call policies of the resulting method overload.]]
  141. [[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.]]
  142. ]
  143. ]]
  144. [[Returns][`*this`]]
  145. ]
  146. ``class_& staticmethod(char const* name);``
  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], and corresponds to a method whose overloads have all been defined.]]
  149. [[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:]]
  150. ]
  151. ``setattr(self, name, staticmethod(getattr(self, name)))``
  152. [variablelist
  153. [[Note][Attempting to invoke def(name,...) after invoking staticmethod(name) will [link raise] a RuntimeError.]]
  154. [[Returns][`*this`]]
  155. ]
  156. ``
  157. template <unspecified>
  158. class_& def(detail::operator_<unspecified>);
  159. ``
  160. [variablelist
  161. [[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].]]
  162. [[Returns][`*this`]]
  163. ]
  164. ``
  165. template <class U>
  166. class_& setattr(char const* name, U const& u);
  167. ``
  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].]]
  170. [[Effects][Converts `u` to Python and adds it to the attribute dictionary of the extension class:
  171. ``PyObject_SetAttrString(this->ptr(), name, object(u).ptr());``]]
  172. [[Returns][`*this`]]
  173. ]
  174. ``
  175. template <class Get>
  176. void add_property(char const* name, Get const& fget, char const* doc=0);
  177. template <class Get, class Set>
  178. void add_property(
  179. char const* name, Get const& fget, Set const& fset, char const* doc=0);
  180. ``
  181. [variablelist
  182. [[Requires][name is an [link ntbs] which conform to Python's [@http://www.python.org/doc/current/ref/identifiers.html identifier naming rules].]]
  183. [[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.]]
  184. [[Returns][`*this`]]
  185. [[Rationale][Allows users to easily expose functions that can be invoked from Python with attribute access syntax.]]
  186. ]
  187. ``
  188. template <class Get>
  189. void add_static_property(char const* name, Get const& fget);
  190. template <class Get, class Set>
  191. void add_static_property(char const* name, Get const& fget, Set const& fset);
  192. ``
  193. [variablelist
  194. [[Requires][name is an [link ntbs] which conforms to Python's [@http://www.python.org/doc/current/ref/identifiers.html identifier naming rules].]]
  195. [[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.]]
  196. [[Returns][`*this`]]
  197. [[Rationale][Allows users to easily expose functions that can be invoked from Python with static attribute access syntax.]]
  198. ]
  199. ``
  200. template <class D>
  201. class_& def_readonly(char const* name, D T::*pm, char const* doc=0);
  202. template <class D>
  203. class_& def_readonly(char const* name, D const& d);
  204. ``
  205. [variablelist
  206. [[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].]]
  207. [[Effects][``this->add_property(name, make_getter(pm), doc);`` and ``this->add_static_property(name, make_getter(d));`` respectively.]]
  208. [[Returns][`*this`]]
  209. [[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.]]
  210. ]
  211. ``
  212. template <class D>
  213. class_& def_readwrite(char const* name, D T::*pm, char const* doc=0);
  214. template <class D>
  215. class_& def_readwrite(char const* name, D& d);
  216. ``
  217. [variablelist
  218. [[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.]]
  219. [[Returns][`*this`]]
  220. [[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.]]
  221. ]
  222. ``
  223. template <typename PickleSuite>
  224. class_& def_pickle(PickleSuite const&);
  225. ``
  226. [variablelist
  227. [[Requires][PickleSuite must be publically derived from [link topics.pickle_support.the_pickle_interface pickle_suite].]]
  228. [[Effects][Defines a legal combination of the special attributes and methods: __getinitargs__, __getstate__, __setstate__, __getstate_manages_dict__, __safe_for_unpickling__, __reduce__]]
  229. [[Returns][`*this`]]
  230. [[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.]]
  231. ]
  232. ``class_& enable_pickling();``
  233. [variablelist
  234. [[Effects][Defines the __reduce__ method and the __safe_for_unpickling__ attribute.]]
  235. [[Returns][`*this`]]
  236. [[Rationale][Light-weight alternative to def_pickle(). Enables implementation of pickle support from Python.]]
  237. ]
  238. [endsect]
  239. [endsect]
  240. [section Class template bases<T1, T2, ...TN>]
  241. An MPL sequence which can be used in class_<...> instantiations indicate a list of base classes.
  242. [section Class template bases synopsis]
  243. ``
  244. namespace boost { namespace python
  245. {
  246. template <T1 = unspecified,...Tn = unspecified>
  247. struct bases
  248. {};
  249. }}
  250. ``
  251. [endsect]
  252. [endsect]
  253. [section Examples]
  254. Given a C++ class declaration:
  255. ``
  256. class Foo : public Bar, public Baz
  257. {
  258. public:
  259. Foo(int x, char const* y);
  260. Foo(double);
  261. std::string const& name() { return m_name; }
  262. void name(char const*);
  263. double value; // public data
  264. private:
  265. ...
  266. };
  267. ``
  268. A corresponding Boost.Python extension class can be created with:
  269. ``
  270. using namespace boost::python;
  271. class_<Foo,bases<Bar,Baz> >("Foo",
  272. "This is Foo's docstring."
  273. "It describes our Foo extension class",
  274. init<int,char const*>(args("x","y"), "__init__ docstring")
  275. )
  276. .def(init<double>())
  277. .def("get_name", &Foo::get_name, return_internal_reference<>())
  278. .def("set_name", &Foo::set_name)
  279. .def_readwrite("value", &Foo::value);
  280. ``
  281. [endsect]
  282. [endsect]