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.

441 lines
13 KiB

2 months ago
  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_MODULE(example, m) {
  20. py::class_<Pet>(m, "Pet")
  21. .def(py::init<const std::string &>())
  22. .def("setName", &Pet::setName)
  23. .def("getName", &Pet::getName);
  24. }
  25. :class:`class_` creates bindings for a C++ *class* or *struct*-style data
  26. structure. :func:`init` is a convenience function that takes the types of a
  27. constructor's parameters as template arguments and wraps the corresponding
  28. constructor (see the :ref:`custom_constructors` section for details). An
  29. interactive Python session demonstrating this example is shown below:
  30. .. code-block:: pycon
  31. % python
  32. >>> import example
  33. >>> p = example.Pet('Molly')
  34. >>> print(p)
  35. <example.Pet object at 0x10cd98060>
  36. >>> p.getName()
  37. u'Molly'
  38. >>> p.setName('Charly')
  39. >>> p.getName()
  40. u'Charly'
  41. .. seealso::
  42. Static member functions can be bound in the same way using
  43. :func:`class_::def_static`.
  44. Keyword and default arguments
  45. =============================
  46. It is possible to specify keyword and default arguments using the syntax
  47. discussed in the previous chapter. Refer to the sections :ref:`keyword_args`
  48. and :ref:`default_args` for details.
  49. Binding lambda functions
  50. ========================
  51. Note how ``print(p)`` produced a rather useless summary of our data structure in the example above:
  52. .. code-block:: pycon
  53. >>> print(p)
  54. <example.Pet object at 0x10cd98060>
  55. To address this, we could bind an utility function that returns a human-readable
  56. summary to the special method slot named ``__repr__``. Unfortunately, there is no
  57. suitable functionality in the ``Pet`` data structure, and it would be nice if
  58. we did not have to change it. This can easily be accomplished by binding a
  59. Lambda function instead:
  60. .. code-block:: cpp
  61. py::class_<Pet>(m, "Pet")
  62. .def(py::init<const std::string &>())
  63. .def("setName", &Pet::setName)
  64. .def("getName", &Pet::getName)
  65. .def("__repr__",
  66. [](const Pet &a) {
  67. return "<example.Pet named '" + a.name + "'>";
  68. }
  69. );
  70. Both stateless [#f1]_ and stateful lambda closures are supported by pybind11.
  71. With the above change, the same Python code now produces the following output:
  72. .. code-block:: pycon
  73. >>> print(p)
  74. <example.Pet named 'Molly'>
  75. .. [#f1] Stateless closures are those with an empty pair of brackets ``[]`` as the capture object.
  76. .. _properties:
  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:: pycon
  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. Please also see the section on
  120. :ref:`static_properties` in the advanced part of the documentation.
  121. Dynamic attributes
  122. ==================
  123. Native Python classes can pick up new attributes dynamically:
  124. .. code-block:: pycon
  125. >>> class Pet:
  126. ... name = 'Molly'
  127. ...
  128. >>> p = Pet()
  129. >>> p.name = 'Charly' # overwrite existing
  130. >>> p.age = 2 # dynamically add a new attribute
  131. By default, classes exported from C++ do not support this and the only writable
  132. attributes are the ones explicitly defined using :func:`class_::def_readwrite`
  133. or :func:`class_::def_property`.
  134. .. code-block:: cpp
  135. py::class_<Pet>(m, "Pet")
  136. .def(py::init<>())
  137. .def_readwrite("name", &Pet::name);
  138. Trying to set any other attribute results in an error:
  139. .. code-block:: pycon
  140. >>> p = example.Pet()
  141. >>> p.name = 'Charly' # OK, attribute defined in C++
  142. >>> p.age = 2 # fail
  143. AttributeError: 'Pet' object has no attribute 'age'
  144. To enable dynamic attributes for C++ classes, the :class:`py::dynamic_attr` tag
  145. must be added to the :class:`py::class_` constructor:
  146. .. code-block:: cpp
  147. py::class_<Pet>(m, "Pet", py::dynamic_attr())
  148. .def(py::init<>())
  149. .def_readwrite("name", &Pet::name);
  150. Now everything works as expected:
  151. .. code-block:: pycon
  152. >>> p = example.Pet()
  153. >>> p.name = 'Charly' # OK, overwrite value in C++
  154. >>> p.age = 2 # OK, dynamically add a new attribute
  155. >>> p.__dict__ # just like a native Python class
  156. {'age': 2}
  157. Note that there is a small runtime cost for a class with dynamic attributes.
  158. Not only because of the addition of a ``__dict__``, but also because of more
  159. expensive garbage collection tracking which must be activated to resolve
  160. possible circular references. Native Python classes incur this same cost by
  161. default, so this is not anything to worry about. By default, pybind11 classes
  162. are more efficient than native Python classes. Enabling dynamic attributes
  163. just brings them on par.
  164. .. _inheritance:
  165. Inheritance
  166. ===========
  167. Suppose now that the example consists of two data structures with an
  168. inheritance relationship:
  169. .. code-block:: cpp
  170. struct Pet {
  171. Pet(const std::string &name) : name(name) { }
  172. std::string name;
  173. };
  174. struct Dog : Pet {
  175. Dog(const std::string &name) : Pet(name) { }
  176. std::string bark() const { return "woof!"; }
  177. };
  178. There are two different ways of indicating a hierarchical relationship to
  179. pybind11: the first specifies the C++ base class as an extra template
  180. parameter of the :class:`class_`:
  181. .. code-block:: cpp
  182. py::class_<Pet>(m, "Pet")
  183. .def(py::init<const std::string &>())
  184. .def_readwrite("name", &Pet::name);
  185. // Method 1: template parameter:
  186. py::class_<Dog, Pet /* <- specify C++ parent type */>(m, "Dog")
  187. .def(py::init<const std::string &>())
  188. .def("bark", &Dog::bark);
  189. Alternatively, we can also assign a name to the previously bound ``Pet``
  190. :class:`class_` object and reference it when binding the ``Dog`` class:
  191. .. code-block:: cpp
  192. py::class_<Pet> pet(m, "Pet");
  193. pet.def(py::init<const std::string &>())
  194. .def_readwrite("name", &Pet::name);
  195. // Method 2: pass parent class_ object:
  196. py::class_<Dog>(m, "Dog", pet /* <- specify Python parent type */)
  197. .def(py::init<const std::string &>())
  198. .def("bark", &Dog::bark);
  199. Functionality-wise, both approaches are equivalent. Afterwards, instances will
  200. expose fields and methods of both types:
  201. .. code-block:: pycon
  202. >>> p = example.Dog('Molly')
  203. >>> p.name
  204. u'Molly'
  205. >>> p.bark()
  206. u'woof!'
  207. Overloaded methods
  208. ==================
  209. Sometimes there are several overloaded C++ methods with the same name taking
  210. different kinds of input arguments:
  211. .. code-block:: cpp
  212. struct Pet {
  213. Pet(const std::string &name, int age) : name(name), age(age) { }
  214. void set(int age_) { age = age_; }
  215. void set(const std::string &name_) { name = name_; }
  216. std::string name;
  217. int age;
  218. };
  219. Attempting to bind ``Pet::set`` will cause an error since the compiler does not
  220. know which method the user intended to select. We can disambiguate by casting
  221. them to function pointers. Binding multiple functions to the same Python name
  222. automatically creates a chain of function overloads that will be tried in
  223. sequence.
  224. .. code-block:: cpp
  225. py::class_<Pet>(m, "Pet")
  226. .def(py::init<const std::string &, int>())
  227. .def("set", (void (Pet::*)(int)) &Pet::set, "Set the pet's age")
  228. .def("set", (void (Pet::*)(const std::string &)) &Pet::set, "Set the pet's name");
  229. The overload signatures are also visible in the method's docstring:
  230. .. code-block:: pycon
  231. >>> help(example.Pet)
  232. class Pet(__builtin__.object)
  233. | Methods defined here:
  234. |
  235. | __init__(...)
  236. | Signature : (Pet, str, int) -> NoneType
  237. |
  238. | set(...)
  239. | 1. Signature : (Pet, int) -> NoneType
  240. |
  241. | Set the pet's age
  242. |
  243. | 2. Signature : (Pet, str) -> NoneType
  244. |
  245. | Set the pet's name
  246. If you have a C++14 compatible compiler [#cpp14]_, you can use an alternative
  247. syntax to cast the overloaded function:
  248. .. code-block:: cpp
  249. py::class_<Pet>(m, "Pet")
  250. .def("set", py::overload_cast<int>(&Pet::set), "Set the pet's age")
  251. .def("set", py::overload_cast<const std::string &>(&Pet::set), "Set the pet's name");
  252. Here, ``py::overload_cast`` only requires the parameter types to be specified.
  253. The return type and class are deduced. This avoids the additional noise of
  254. ``void (Pet::*)()`` as seen in the raw cast. If a function is overloaded based
  255. on constness, the ``py::const_`` tag should be used:
  256. .. code-block:: cpp
  257. struct Widget {
  258. int foo(int x, float y);
  259. int foo(int x, float y) const;
  260. };
  261. py::class_<Widget>(m, "Widget")
  262. .def("foo_mutable", py::overload_cast<int, float>(&Widget::foo))
  263. .def("foo_const", py::overload_cast<int, float>(&Widget::foo, py::const_));
  264. .. [#cpp14] A compiler which supports the ``-std=c++14`` flag
  265. or Visual Studio 2015 Update 2 and newer.
  266. .. note::
  267. To define multiple overloaded constructors, simply declare one after the
  268. other using the ``.def(py::init<...>())`` syntax. The existing machinery
  269. for specifying keyword and default arguments also works.
  270. Enumerations and internal types
  271. ===============================
  272. Let's now suppose that the example class contains an internal enumeration type,
  273. e.g.:
  274. .. code-block:: cpp
  275. struct Pet {
  276. enum Kind {
  277. Dog = 0,
  278. Cat
  279. };
  280. Pet(const std::string &name, Kind type) : name(name), type(type) { }
  281. std::string name;
  282. Kind type;
  283. };
  284. The binding code for this example looks as follows:
  285. .. code-block:: cpp
  286. py::class_<Pet> pet(m, "Pet");
  287. pet.def(py::init<const std::string &, Pet::Kind>())
  288. .def_readwrite("name", &Pet::name)
  289. .def_readwrite("type", &Pet::type);
  290. py::enum_<Pet::Kind>(pet, "Kind")
  291. .value("Dog", Pet::Kind::Dog)
  292. .value("Cat", Pet::Kind::Cat)
  293. .export_values();
  294. To ensure that the ``Kind`` type is created within the scope of ``Pet``, the
  295. ``pet`` :class:`class_` instance must be supplied to the :class:`enum_`.
  296. constructor. The :func:`enum_::export_values` function exports the enum entries
  297. into the parent scope, which should be skipped for newer C++11-style strongly
  298. typed enums.
  299. .. code-block:: pycon
  300. >>> p = Pet('Lucy', Pet.Cat)
  301. >>> p.type
  302. Kind.Cat
  303. >>> int(p.type)
  304. 1L
  305. The entries defined by the enumeration type are exposed in the ``__members__`` property:
  306. .. code-block:: pycon
  307. >>> Pet.Kind.__members__
  308. {'Dog': Kind.Dog, 'Cat': Kind.Cat}
  309. .. note::
  310. When the special tag ``py::arithmetic()`` is specified to the ``enum_``
  311. constructor, pybind11 creates an enumeration that also supports rudimentary
  312. arithmetic and bit-level operations like comparisons, and, or, xor, negation,
  313. etc.
  314. .. code-block:: cpp
  315. py::enum_<Pet::Kind>(pet, "Kind", py::arithmetic())
  316. ...
  317. By default, these are omitted to conserve space.