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.

331 lines
9.2 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:: python
  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:: python
  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:: python
  75. >>> print(p)
  76. <example.Pet named 'Molly'>
  77. Instance and static fields
  78. ==========================
  79. We can also directly expose the ``name`` field using the
  80. :func:`class_::def_readwrite` method. A similar :func:`class_::def_readonly`
  81. method also exists for ``const`` fields.
  82. .. code-block:: cpp
  83. py::class_<Pet>(m, "Pet")
  84. .def(py::init<const std::string &>())
  85. .def_readwrite("name", &Pet::name)
  86. // ... remainder ...
  87. This makes it possible to write
  88. .. code-block:: python
  89. >>> p = example.Pet('Molly')
  90. >>> p.name
  91. u'Molly'
  92. >>> p.name = 'Charly'
  93. >>> p.name
  94. u'Charly'
  95. Now suppose that ``Pet::name`` was a private internal variable
  96. that can only be accessed via setters and getters.
  97. .. code-block:: cpp
  98. class Pet {
  99. public:
  100. Pet(const std::string &name) : name(name) { }
  101. void setName(const std::string &name_) { name = name_; }
  102. const std::string &getName() const { return name; }
  103. private:
  104. std::string name;
  105. };
  106. In this case, the method :func:`class_::def_property`
  107. (:func:`class_::def_property_readonly` for read-only data) can be used to
  108. provide a field-like interface within Python that will transparently call
  109. the setter and getter functions:
  110. .. code-block:: cpp
  111. py::class_<Pet>(m, "Pet")
  112. .def(py::init<const std::string &>())
  113. .def_property("name", &Pet::getName, &Pet::setName)
  114. // ... remainder ...
  115. .. seealso::
  116. Similar functions :func:`class_::def_readwrite_static`,
  117. :func:`class_::def_readonly_static` :func:`class_::def_property_static`,
  118. and :func:`class_::def_property_readonly_static` are provided for binding
  119. static variables and properties.
  120. .. _inheritance:
  121. Inheritance
  122. ===========
  123. Suppose now that the example consists of two data structures with an
  124. inheritance relationship:
  125. .. code-block:: cpp
  126. struct Pet {
  127. Pet(const std::string &name) : name(name) { }
  128. std::string name;
  129. };
  130. struct Dog : Pet {
  131. Dog(const std::string &name) : Pet(name) { }
  132. std::string bark() const { return "woof!"; }
  133. };
  134. There are two different ways of indicating a hierarchical relationship to
  135. pybind11: the first is by specifying the C++ base class explicitly during
  136. construction using the ``base`` attribute:
  137. .. code-block:: cpp
  138. py::class_<Pet>(m, "Pet")
  139. .def(py::init<const std::string &>())
  140. .def_readwrite("name", &Pet::name);
  141. py::class_<Dog>(m, "Dog", py::base<Pet>() /* <- specify C++ parent type */)
  142. .def(py::init<const std::string &>())
  143. .def("bark", &Dog::bark);
  144. Alternatively, we can also assign a name to the previously bound ``Pet``
  145. :class:`class_` object and reference it when binding the ``Dog`` class:
  146. .. code-block:: cpp
  147. py::class_<Pet> pet(m, "Pet");
  148. pet.def(py::init<const std::string &>())
  149. .def_readwrite("name", &Pet::name);
  150. py::class_<Dog>(m, "Dog", pet /* <- specify Python parent type */)
  151. .def(py::init<const std::string &>())
  152. .def("bark", &Dog::bark);
  153. Functionality-wise, both approaches are completely equivalent. Afterwards,
  154. instances will expose fields and methods of both types:
  155. .. code-block:: python
  156. >>> p = example.Dog('Molly')
  157. >>> p.name
  158. u'Molly'
  159. >>> p.bark()
  160. u'woof!'
  161. Overloaded methods
  162. ==================
  163. Sometimes there are several overloaded C++ methods with the same name taking
  164. different kinds of input arguments:
  165. .. code-block:: cpp
  166. struct Pet {
  167. Pet(const std::string &name, int age) : name(name), age(age) { }
  168. void set(int age) { age = age; }
  169. void set(const std::string &name) { name = name; }
  170. std::string name;
  171. int age;
  172. };
  173. Attempting to bind ``Pet::set`` will cause an error since the compiler does not
  174. know which method the user intended to select. We can disambiguate by casting
  175. them to function pointers. Binding multiple functions to the same Python name
  176. automatically creates a chain of function overloads that will be tried in
  177. sequence.
  178. .. code-block:: cpp
  179. py::class_<Pet>(m, "Pet")
  180. .def(py::init<const std::string &, int>())
  181. .def("set", (void (Pet::*)(int)) &Pet::set, "Set the pet's age")
  182. .def("set", (void (Pet::*)(const std::string &)) &Pet::set, "Set the pet's name");
  183. The overload signatures are also visible in the method's docstring:
  184. .. code-block:: python
  185. >>> help(example.Pet)
  186. class Pet(__builtin__.object)
  187. | Methods defined here:
  188. |
  189. | __init__(...)
  190. | Signature : (Pet, str, int) -> NoneType
  191. |
  192. | set(...)
  193. | 1. Signature : (Pet, int) -> NoneType
  194. |
  195. | Set the pet's age
  196. |
  197. | 2. Signature : (Pet, str) -> NoneType
  198. |
  199. | Set the pet's name
  200. .. note::
  201. To define multiple overloaded constructors, simply declare one after the
  202. other using the ``.def(py::init<...>())`` syntax. The existing machinery
  203. for specifying keyword and default arguments also works.
  204. Enumerations and internal types
  205. ===============================
  206. Let's now suppose that the example class contains an internal enumeration type,
  207. e.g.:
  208. .. code-block:: cpp
  209. struct Pet {
  210. enum Kind {
  211. Dog = 0,
  212. Cat
  213. };
  214. Pet(const std::string &name, Kind type) : name(name), type(type) { }
  215. std::string name;
  216. Kind type;
  217. };
  218. The binding code for this example looks as follows:
  219. .. code-block:: cpp
  220. py::class_<Pet> pet(m, "Pet");
  221. pet.def(py::init<const std::string &, Pet::Kind>())
  222. .def_readwrite("name", &Pet::name)
  223. .def_readwrite("type", &Pet::type);
  224. py::enum_<Pet::Kind>(pet, "Kind")
  225. .value("Dog", Pet::Kind::Dog)
  226. .value("Cat", Pet::Kind::Cat)
  227. .export_values();
  228. To ensure that the ``Kind`` type is created within the scope of ``Pet``, the
  229. ``pet`` :class:`class_` instance must be supplied to the :class:`enum_`.
  230. constructor. The :func:`enum_::export_values` function exports the enum entries
  231. into the parent scope, which should be skipped for newer C++11-style strongly
  232. typed enums.
  233. .. code-block:: python
  234. >>> p = Pet('Lucy', Pet.Cat)
  235. >>> p.type
  236. Kind.Cat
  237. >>> int(p.type)
  238. 1L
  239. .. [#f1] Stateless closures are those with an empty pair of brackets ``[]`` as the capture object.