You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

334 lines
9.3 KiB

  1. .. _classes:
  2. Object-oriented code
  3. ####################
  4. Creating bindings for a custom type
  5. ===================================
  6. Let's now look at a more complex example where we'll create bindings for a
  7. custom C++ data structure named ``Pet``. Its definition is given below:
  8. .. code-block:: cpp
  9. struct Pet {
  10. Pet(const std::string &name) : name(name) { }
  11. void setName(const std::string &name_) { name = name_; }
  12. const std::string &getName() const { return name; }
  13. std::string name;
  14. };
  15. The binding code for ``Pet`` looks as follows:
  16. .. code-block:: cpp
  17. #include <pybind11/pybind11.h>
  18. namespace py = pybind11;
  19. PYBIND11_PLUGIN(example) {
  20. py::module m("example", "pybind11 example plugin");
  21. py::class_<Pet>(m, "Pet")
  22. .def(py::init<const std::string &>())
  23. .def("setName", &Pet::setName)
  24. .def("getName", &Pet::getName);
  25. return m.ptr();
  26. }
  27. :class:`class_` creates bindings for a C++ `class` or `struct`-style data
  28. structure. :func:`init` is a convenience function that takes the types of a
  29. constructor's parameters as template arguments and wraps the corresponding
  30. constructor (see the :ref:`custom_constructors` section for details). An
  31. interactive Python session demonstrating this example is shown below:
  32. .. code-block:: pycon
  33. % python
  34. >>> import example
  35. >>> p = example.Pet('Molly')
  36. >>> print(p)
  37. <example.Pet object at 0x10cd98060>
  38. >>> p.getName()
  39. u'Molly'
  40. >>> p.setName('Charly')
  41. >>> p.getName()
  42. u'Charly'
  43. .. seealso::
  44. Static member functions can be bound in the same way using
  45. :func:`class_::def_static`.
  46. Keyword and default arguments
  47. =============================
  48. It is possible to specify keyword and default arguments using the syntax
  49. discussed in the previous chapter. Refer to the sections :ref:`keyword_args`
  50. and :ref:`default_args` for details.
  51. Binding lambda functions
  52. ========================
  53. Note how ``print(p)`` produced a rather useless summary of our data structure in the example above:
  54. .. code-block:: pycon
  55. >>> print(p)
  56. <example.Pet object at 0x10cd98060>
  57. To address this, we could bind an utility function that returns a human-readable
  58. summary to the special method slot named ``__repr__``. Unfortunately, there is no
  59. suitable functionality in the ``Pet`` data structure, and it would be nice if
  60. we did not have to change it. This can easily be accomplished by binding a
  61. Lambda function instead:
  62. .. code-block:: cpp
  63. py::class_<Pet>(m, "Pet")
  64. .def(py::init<const std::string &>())
  65. .def("setName", &Pet::setName)
  66. .def("getName", &Pet::getName)
  67. .def("__repr__",
  68. [](const Pet &a) {
  69. return "<example.Pet named '" + a.name + "'>";
  70. }
  71. );
  72. Both stateless [#f1]_ and stateful lambda closures are supported by pybind11.
  73. With the above change, the same Python code now produces the following output:
  74. .. code-block:: pycon
  75. >>> print(p)
  76. <example.Pet named 'Molly'>
  77. .. _properties:
  78. Instance and static fields
  79. ==========================
  80. We can also directly expose the ``name`` field using the
  81. :func:`class_::def_readwrite` method. A similar :func:`class_::def_readonly`
  82. method also exists for ``const`` fields.
  83. .. code-block:: cpp
  84. py::class_<Pet>(m, "Pet")
  85. .def(py::init<const std::string &>())
  86. .def_readwrite("name", &Pet::name)
  87. // ... remainder ...
  88. This makes it possible to write
  89. .. code-block:: pycon
  90. >>> p = example.Pet('Molly')
  91. >>> p.name
  92. u'Molly'
  93. >>> p.name = 'Charly'
  94. >>> p.name
  95. u'Charly'
  96. Now suppose that ``Pet::name`` was a private internal variable
  97. that can only be accessed via setters and getters.
  98. .. code-block:: cpp
  99. class Pet {
  100. public:
  101. Pet(const std::string &name) : name(name) { }
  102. void setName(const std::string &name_) { name = name_; }
  103. const std::string &getName() const { return name; }
  104. private:
  105. std::string name;
  106. };
  107. In this case, the method :func:`class_::def_property`
  108. (:func:`class_::def_property_readonly` for read-only data) can be used to
  109. provide a field-like interface within Python that will transparently call
  110. the setter and getter functions:
  111. .. code-block:: cpp
  112. py::class_<Pet>(m, "Pet")
  113. .def(py::init<const std::string &>())
  114. .def_property("name", &Pet::getName, &Pet::setName)
  115. // ... remainder ...
  116. .. seealso::
  117. Similar functions :func:`class_::def_readwrite_static`,
  118. :func:`class_::def_readonly_static` :func:`class_::def_property_static`,
  119. and :func:`class_::def_property_readonly_static` are provided for binding
  120. static variables and properties. Please also see the section on
  121. :ref:`static_properties` in the advanced part of the documentation.
  122. .. _inheritance:
  123. Inheritance
  124. ===========
  125. Suppose now that the example consists of two data structures with an
  126. inheritance relationship:
  127. .. code-block:: cpp
  128. struct Pet {
  129. Pet(const std::string &name) : name(name) { }
  130. std::string name;
  131. };
  132. struct Dog : Pet {
  133. Dog(const std::string &name) : Pet(name) { }
  134. std::string bark() const { return "woof!"; }
  135. };
  136. There are two different ways of indicating a hierarchical relationship to
  137. pybind11: the first is by specifying the C++ base class explicitly during
  138. construction using the ``base`` attribute:
  139. .. code-block:: cpp
  140. py::class_<Pet>(m, "Pet")
  141. .def(py::init<const std::string &>())
  142. .def_readwrite("name", &Pet::name);
  143. py::class_<Dog>(m, "Dog", py::base<Pet>() /* <- specify C++ parent type */)
  144. .def(py::init<const std::string &>())
  145. .def("bark", &Dog::bark);
  146. Alternatively, we can also assign a name to the previously bound ``Pet``
  147. :class:`class_` object and reference it when binding the ``Dog`` class:
  148. .. code-block:: cpp
  149. py::class_<Pet> pet(m, "Pet");
  150. pet.def(py::init<const std::string &>())
  151. .def_readwrite("name", &Pet::name);
  152. py::class_<Dog>(m, "Dog", pet /* <- specify Python parent type */)
  153. .def(py::init<const std::string &>())
  154. .def("bark", &Dog::bark);
  155. Functionality-wise, both approaches are completely equivalent. Afterwards,
  156. instances will expose fields and methods of both types:
  157. .. code-block:: pycon
  158. >>> p = example.Dog('Molly')
  159. >>> p.name
  160. u'Molly'
  161. >>> p.bark()
  162. u'woof!'
  163. Overloaded methods
  164. ==================
  165. Sometimes there are several overloaded C++ methods with the same name taking
  166. different kinds of input arguments:
  167. .. code-block:: cpp
  168. struct Pet {
  169. Pet(const std::string &name, int age) : name(name), age(age) { }
  170. void set(int age) { age = age; }
  171. void set(const std::string &name) { name = name; }
  172. std::string name;
  173. int age;
  174. };
  175. Attempting to bind ``Pet::set`` will cause an error since the compiler does not
  176. know which method the user intended to select. We can disambiguate by casting
  177. them to function pointers. Binding multiple functions to the same Python name
  178. automatically creates a chain of function overloads that will be tried in
  179. sequence.
  180. .. code-block:: cpp
  181. py::class_<Pet>(m, "Pet")
  182. .def(py::init<const std::string &, int>())
  183. .def("set", (void (Pet::*)(int)) &Pet::set, "Set the pet's age")
  184. .def("set", (void (Pet::*)(const std::string &)) &Pet::set, "Set the pet's name");
  185. The overload signatures are also visible in the method's docstring:
  186. .. code-block:: pycon
  187. >>> help(example.Pet)
  188. class Pet(__builtin__.object)
  189. | Methods defined here:
  190. |
  191. | __init__(...)
  192. | Signature : (Pet, str, int) -> NoneType
  193. |
  194. | set(...)
  195. | 1. Signature : (Pet, int) -> NoneType
  196. |
  197. | Set the pet's age
  198. |
  199. | 2. Signature : (Pet, str) -> NoneType
  200. |
  201. | Set the pet's name
  202. .. note::
  203. To define multiple overloaded constructors, simply declare one after the
  204. other using the ``.def(py::init<...>())`` syntax. The existing machinery
  205. for specifying keyword and default arguments also works.
  206. Enumerations and internal types
  207. ===============================
  208. Let's now suppose that the example class contains an internal enumeration type,
  209. e.g.:
  210. .. code-block:: cpp
  211. struct Pet {
  212. enum Kind {
  213. Dog = 0,
  214. Cat
  215. };
  216. Pet(const std::string &name, Kind type) : name(name), type(type) { }
  217. std::string name;
  218. Kind type;
  219. };
  220. The binding code for this example looks as follows:
  221. .. code-block:: cpp
  222. py::class_<Pet> pet(m, "Pet");
  223. pet.def(py::init<const std::string &, Pet::Kind>())
  224. .def_readwrite("name", &Pet::name)
  225. .def_readwrite("type", &Pet::type);
  226. py::enum_<Pet::Kind>(pet, "Kind")
  227. .value("Dog", Pet::Kind::Dog)
  228. .value("Cat", Pet::Kind::Cat)
  229. .export_values();
  230. To ensure that the ``Kind`` type is created within the scope of ``Pet``, the
  231. ``pet`` :class:`class_` instance must be supplied to the :class:`enum_`.
  232. constructor. The :func:`enum_::export_values` function exports the enum entries
  233. into the parent scope, which should be skipped for newer C++11-style strongly
  234. typed enums.
  235. .. code-block:: pycon
  236. >>> p = Pet('Lucy', Pet.Cat)
  237. >>> p.type
  238. Kind.Cat
  239. >>> int(p.type)
  240. 1L
  241. .. [#f1] Stateless closures are those with an empty pair of brackets ``[]`` as the capture object.