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.

410 lines
12 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. Dynamic attributes
  123. ==================
  124. Native Python classes can pick up new attributes dynamically:
  125. .. code-block:: pycon
  126. >>> class Pet:
  127. ... name = 'Molly'
  128. ...
  129. >>> p = Pet()
  130. >>> p.name = 'Charly' # overwrite existing
  131. >>> p.age = 2 # dynamically add a new attribute
  132. By default, classes exported from C++ do not support this and the only writable
  133. attributes are the ones explicitly defined using :func:`class_::def_readwrite`
  134. or :func:`class_::def_property`.
  135. .. code-block:: cpp
  136. py::class_<Pet>(m, "Pet")
  137. .def(py::init<>())
  138. .def_readwrite("name", &Pet::name);
  139. Trying to set any other attribute results in an error:
  140. .. code-block:: pycon
  141. >>> p = example.Pet()
  142. >>> p.name = 'Charly' # OK, attribute defined in C++
  143. >>> p.age = 2 # fail
  144. AttributeError: 'Pet' object has no attribute 'age'
  145. To enable dynamic attributes for C++ classes, the :class:`py::dynamic_attr` tag
  146. must be added to the :class:`py::class_` constructor:
  147. .. code-block:: cpp
  148. py::class_<Pet>(m, "Pet", py::dynamic_attr())
  149. .def(py::init<>())
  150. .def_readwrite("name", &Pet::name);
  151. Now everything works as expected:
  152. .. code-block:: pycon
  153. >>> p = example.Pet()
  154. >>> p.name = 'Charly' # OK, overwrite value in C++
  155. >>> p.age = 2 # OK, dynamically add a new attribute
  156. >>> p.__dict__ # just like a native Python class
  157. {'age': 2}
  158. Note that there is a small runtime cost for a class with dynamic attributes.
  159. Not only because of the addition of a ``__dict__``, but also because of more
  160. expensive garbage collection tracking which must be activated to resolve
  161. possible circular references. Native Python classes incur this same cost by
  162. default, so this is not anything to worry about. By default, pybind11 classes
  163. are more efficient than native Python classes. Enabling dynamic attributes
  164. just brings them on par.
  165. .. _inheritance:
  166. Inheritance
  167. ===========
  168. Suppose now that the example consists of two data structures with an
  169. inheritance relationship:
  170. .. code-block:: cpp
  171. struct Pet {
  172. Pet(const std::string &name) : name(name) { }
  173. std::string name;
  174. };
  175. struct Dog : Pet {
  176. Dog(const std::string &name) : Pet(name) { }
  177. std::string bark() const { return "woof!"; }
  178. };
  179. There are two different ways of indicating a hierarchical relationship to
  180. pybind11: the first specifies the C++ base class as an extra template
  181. parameter of the :class:`class_`:
  182. .. code-block:: cpp
  183. py::class_<Pet>(m, "Pet")
  184. .def(py::init<const std::string &>())
  185. .def_readwrite("name", &Pet::name);
  186. // Method 1: template parameter:
  187. py::class_<Dog, Pet /* <- specify C++ parent type */>(m, "Dog")
  188. .def(py::init<const std::string &>())
  189. .def("bark", &Dog::bark);
  190. Alternatively, we can also assign a name to the previously bound ``Pet``
  191. :class:`class_` object and reference it when binding the ``Dog`` class:
  192. .. code-block:: cpp
  193. py::class_<Pet> pet(m, "Pet");
  194. pet.def(py::init<const std::string &>())
  195. .def_readwrite("name", &Pet::name);
  196. // Method 2: pass parent class_ object:
  197. py::class_<Dog>(m, "Dog", pet /* <- specify Python parent type */)
  198. .def(py::init<const std::string &>())
  199. .def("bark", &Dog::bark);
  200. Functionality-wise, both approaches are equivalent. Afterwards, instances will
  201. expose fields and methods of both types:
  202. .. code-block:: pycon
  203. >>> p = example.Dog('Molly')
  204. >>> p.name
  205. u'Molly'
  206. >>> p.bark()
  207. u'woof!'
  208. Overloaded methods
  209. ==================
  210. Sometimes there are several overloaded C++ methods with the same name taking
  211. different kinds of input arguments:
  212. .. code-block:: cpp
  213. struct Pet {
  214. Pet(const std::string &name, int age) : name(name), age(age) { }
  215. void set(int age) { age = age; }
  216. void set(const std::string &name) { name = name; }
  217. std::string name;
  218. int age;
  219. };
  220. Attempting to bind ``Pet::set`` will cause an error since the compiler does not
  221. know which method the user intended to select. We can disambiguate by casting
  222. them to function pointers. Binding multiple functions to the same Python name
  223. automatically creates a chain of function overloads that will be tried in
  224. sequence.
  225. .. code-block:: cpp
  226. py::class_<Pet>(m, "Pet")
  227. .def(py::init<const std::string &, int>())
  228. .def("set", (void (Pet::*)(int)) &Pet::set, "Set the pet's age")
  229. .def("set", (void (Pet::*)(const std::string &)) &Pet::set, "Set the pet's name");
  230. The overload signatures are also visible in the method's docstring:
  231. .. code-block:: pycon
  232. >>> help(example.Pet)
  233. class Pet(__builtin__.object)
  234. | Methods defined here:
  235. |
  236. | __init__(...)
  237. | Signature : (Pet, str, int) -> NoneType
  238. |
  239. | set(...)
  240. | 1. Signature : (Pet, int) -> NoneType
  241. |
  242. | Set the pet's age
  243. |
  244. | 2. Signature : (Pet, str) -> NoneType
  245. |
  246. | Set the pet's name
  247. .. note::
  248. To define multiple overloaded constructors, simply declare one after the
  249. other using the ``.def(py::init<...>())`` syntax. The existing machinery
  250. for specifying keyword and default arguments also works.
  251. Enumerations and internal types
  252. ===============================
  253. Let's now suppose that the example class contains an internal enumeration type,
  254. e.g.:
  255. .. code-block:: cpp
  256. struct Pet {
  257. enum Kind {
  258. Dog = 0,
  259. Cat
  260. };
  261. Pet(const std::string &name, Kind type) : name(name), type(type) { }
  262. std::string name;
  263. Kind type;
  264. };
  265. The binding code for this example looks as follows:
  266. .. code-block:: cpp
  267. py::class_<Pet> pet(m, "Pet");
  268. pet.def(py::init<const std::string &, Pet::Kind>())
  269. .def_readwrite("name", &Pet::name)
  270. .def_readwrite("type", &Pet::type);
  271. py::enum_<Pet::Kind>(pet, "Kind")
  272. .value("Dog", Pet::Kind::Dog)
  273. .value("Cat", Pet::Kind::Cat)
  274. .export_values();
  275. To ensure that the ``Kind`` type is created within the scope of ``Pet``, the
  276. ``pet`` :class:`class_` instance must be supplied to the :class:`enum_`.
  277. constructor. The :func:`enum_::export_values` function exports the enum entries
  278. into the parent scope, which should be skipped for newer C++11-style strongly
  279. typed enums.
  280. .. code-block:: pycon
  281. >>> p = Pet('Lucy', Pet.Cat)
  282. >>> p.type
  283. Kind.Cat
  284. >>> int(p.type)
  285. 1L
  286. .. note::
  287. When the special tag ``py::arithmetic()`` is specified to the ``enum_``
  288. constructor, pybind11 creates an enumeration that also supports rudimentary
  289. arithmetic and bit-level operations like comparisons, and, or, xor, negation,
  290. etc.
  291. .. code-block:: cpp
  292. py::enum_<Pet::Kind>(pet, "Kind", py::arithmetic())
  293. ...
  294. By default, these are omitted to conserve space.
  295. .. [#f1] Stateless closures are those with an empty pair of brackets ``[]`` as the capture object.