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.

445 lines
13 KiB

8 years 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_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. .. [#f1] Stateless closures are those with an empty pair of brackets ``[]`` as the capture object.
  78. .. _properties:
  79. Instance and static fields
  80. ==========================
  81. We can also directly expose the ``name`` field using the
  82. :func:`class_::def_readwrite` method. A similar :func:`class_::def_readonly`
  83. method also exists for ``const`` fields.
  84. .. code-block:: cpp
  85. py::class_<Pet>(m, "Pet")
  86. .def(py::init<const std::string &>())
  87. .def_readwrite("name", &Pet::name)
  88. // ... remainder ...
  89. This makes it possible to write
  90. .. code-block:: pycon
  91. >>> p = example.Pet('Molly')
  92. >>> p.name
  93. u'Molly'
  94. >>> p.name = 'Charly'
  95. >>> p.name
  96. u'Charly'
  97. Now suppose that ``Pet::name`` was a private internal variable
  98. that can only be accessed via setters and getters.
  99. .. code-block:: cpp
  100. class Pet {
  101. public:
  102. Pet(const std::string &name) : name(name) { }
  103. void setName(const std::string &name_) { name = name_; }
  104. const std::string &getName() const { return name; }
  105. private:
  106. std::string name;
  107. };
  108. In this case, the method :func:`class_::def_property`
  109. (:func:`class_::def_property_readonly` for read-only data) can be used to
  110. provide a field-like interface within Python that will transparently call
  111. the setter and getter functions:
  112. .. code-block:: cpp
  113. py::class_<Pet>(m, "Pet")
  114. .def(py::init<const std::string &>())
  115. .def_property("name", &Pet::getName, &Pet::setName)
  116. // ... remainder ...
  117. .. seealso::
  118. Similar functions :func:`class_::def_readwrite_static`,
  119. :func:`class_::def_readonly_static` :func:`class_::def_property_static`,
  120. and :func:`class_::def_property_readonly_static` are provided for binding
  121. static variables and properties. Please also see the section on
  122. :ref:`static_properties` in the advanced part of the documentation.
  123. Dynamic attributes
  124. ==================
  125. Native Python classes can pick up new attributes dynamically:
  126. .. code-block:: pycon
  127. >>> class Pet:
  128. ... name = 'Molly'
  129. ...
  130. >>> p = Pet()
  131. >>> p.name = 'Charly' # overwrite existing
  132. >>> p.age = 2 # dynamically add a new attribute
  133. By default, classes exported from C++ do not support this and the only writable
  134. attributes are the ones explicitly defined using :func:`class_::def_readwrite`
  135. or :func:`class_::def_property`.
  136. .. code-block:: cpp
  137. py::class_<Pet>(m, "Pet")
  138. .def(py::init<>())
  139. .def_readwrite("name", &Pet::name);
  140. Trying to set any other attribute results in an error:
  141. .. code-block:: pycon
  142. >>> p = example.Pet()
  143. >>> p.name = 'Charly' # OK, attribute defined in C++
  144. >>> p.age = 2 # fail
  145. AttributeError: 'Pet' object has no attribute 'age'
  146. To enable dynamic attributes for C++ classes, the :class:`py::dynamic_attr` tag
  147. must be added to the :class:`py::class_` constructor:
  148. .. code-block:: cpp
  149. py::class_<Pet>(m, "Pet", py::dynamic_attr())
  150. .def(py::init<>())
  151. .def_readwrite("name", &Pet::name);
  152. Now everything works as expected:
  153. .. code-block:: pycon
  154. >>> p = example.Pet()
  155. >>> p.name = 'Charly' # OK, overwrite value in C++
  156. >>> p.age = 2 # OK, dynamically add a new attribute
  157. >>> p.__dict__ # just like a native Python class
  158. {'age': 2}
  159. Note that there is a small runtime cost for a class with dynamic attributes.
  160. Not only because of the addition of a ``__dict__``, but also because of more
  161. expensive garbage collection tracking which must be activated to resolve
  162. possible circular references. Native Python classes incur this same cost by
  163. default, so this is not anything to worry about. By default, pybind11 classes
  164. are more efficient than native Python classes. Enabling dynamic attributes
  165. just brings them on par.
  166. .. _inheritance:
  167. Inheritance
  168. ===========
  169. Suppose now that the example consists of two data structures with an
  170. inheritance relationship:
  171. .. code-block:: cpp
  172. struct Pet {
  173. Pet(const std::string &name) : name(name) { }
  174. std::string name;
  175. };
  176. struct Dog : Pet {
  177. Dog(const std::string &name) : Pet(name) { }
  178. std::string bark() const { return "woof!"; }
  179. };
  180. There are two different ways of indicating a hierarchical relationship to
  181. pybind11: the first specifies the C++ base class as an extra template
  182. parameter of the :class:`class_`:
  183. .. code-block:: cpp
  184. py::class_<Pet>(m, "Pet")
  185. .def(py::init<const std::string &>())
  186. .def_readwrite("name", &Pet::name);
  187. // Method 1: template parameter:
  188. py::class_<Dog, Pet /* <- specify C++ parent type */>(m, "Dog")
  189. .def(py::init<const std::string &>())
  190. .def("bark", &Dog::bark);
  191. Alternatively, we can also assign a name to the previously bound ``Pet``
  192. :class:`class_` object and reference it when binding the ``Dog`` class:
  193. .. code-block:: cpp
  194. py::class_<Pet> pet(m, "Pet");
  195. pet.def(py::init<const std::string &>())
  196. .def_readwrite("name", &Pet::name);
  197. // Method 2: pass parent class_ object:
  198. py::class_<Dog>(m, "Dog", pet /* <- specify Python parent type */)
  199. .def(py::init<const std::string &>())
  200. .def("bark", &Dog::bark);
  201. Functionality-wise, both approaches are equivalent. Afterwards, instances will
  202. expose fields and methods of both types:
  203. .. code-block:: pycon
  204. >>> p = example.Dog('Molly')
  205. >>> p.name
  206. u'Molly'
  207. >>> p.bark()
  208. u'woof!'
  209. Overloaded methods
  210. ==================
  211. Sometimes there are several overloaded C++ methods with the same name taking
  212. different kinds of input arguments:
  213. .. code-block:: cpp
  214. struct Pet {
  215. Pet(const std::string &name, int age) : name(name), age(age) { }
  216. void set(int age_) { age = age_; }
  217. void set(const std::string &name_) { name = name_; }
  218. std::string name;
  219. int age;
  220. };
  221. Attempting to bind ``Pet::set`` will cause an error since the compiler does not
  222. know which method the user intended to select. We can disambiguate by casting
  223. them to function pointers. Binding multiple functions to the same Python name
  224. automatically creates a chain of function overloads that will be tried in
  225. sequence.
  226. .. code-block:: cpp
  227. py::class_<Pet>(m, "Pet")
  228. .def(py::init<const std::string &, int>())
  229. .def("set", (void (Pet::*)(int)) &Pet::set, "Set the pet's age")
  230. .def("set", (void (Pet::*)(const std::string &)) &Pet::set, "Set the pet's name");
  231. The overload signatures are also visible in the method's docstring:
  232. .. code-block:: pycon
  233. >>> help(example.Pet)
  234. class Pet(__builtin__.object)
  235. | Methods defined here:
  236. |
  237. | __init__(...)
  238. | Signature : (Pet, str, int) -> NoneType
  239. |
  240. | set(...)
  241. | 1. Signature : (Pet, int) -> NoneType
  242. |
  243. | Set the pet's age
  244. |
  245. | 2. Signature : (Pet, str) -> NoneType
  246. |
  247. | Set the pet's name
  248. If you have a C++14 compatible compiler [#cpp14]_, you can use an alternative
  249. syntax to cast the overloaded function:
  250. .. code-block:: cpp
  251. py::class_<Pet>(m, "Pet")
  252. .def("set", py::overload_cast<int>(&Pet::set), "Set the pet's age")
  253. .def("set", py::overload_cast<const std::string &>(&Pet::set), "Set the pet's name");
  254. Here, ``py::overload_cast`` only requires the parameter types to be specified.
  255. The return type and class are deduced. This avoids the additional noise of
  256. ``void (Pet::*)()`` as seen in the raw cast. If a function is overloaded based
  257. on constness, the ``py::const_`` tag should be used:
  258. .. code-block:: cpp
  259. struct Widget {
  260. int foo(int x, float y);
  261. int foo(int x, float y) const;
  262. };
  263. py::class_<Widget>(m, "Widget")
  264. .def("foo_mutable", py::overload_cast<int, float>(&Widget::foo))
  265. .def("foo_const", py::overload_cast<int, float>(&Widget::foo, py::const_));
  266. .. [#cpp14] A compiler which supports the ``-std=c++14`` flag
  267. or Visual Studio 2015 Update 2 and newer.
  268. .. note::
  269. To define multiple overloaded constructors, simply declare one after the
  270. other using the ``.def(py::init<...>())`` syntax. The existing machinery
  271. for specifying keyword and default arguments also works.
  272. Enumerations and internal types
  273. ===============================
  274. Let's now suppose that the example class contains an internal enumeration type,
  275. e.g.:
  276. .. code-block:: cpp
  277. struct Pet {
  278. enum Kind {
  279. Dog = 0,
  280. Cat
  281. };
  282. Pet(const std::string &name, Kind type) : name(name), type(type) { }
  283. std::string name;
  284. Kind type;
  285. };
  286. The binding code for this example looks as follows:
  287. .. code-block:: cpp
  288. py::class_<Pet> pet(m, "Pet");
  289. pet.def(py::init<const std::string &, Pet::Kind>())
  290. .def_readwrite("name", &Pet::name)
  291. .def_readwrite("type", &Pet::type);
  292. py::enum_<Pet::Kind>(pet, "Kind")
  293. .value("Dog", Pet::Kind::Dog)
  294. .value("Cat", Pet::Kind::Cat)
  295. .export_values();
  296. To ensure that the ``Kind`` type is created within the scope of ``Pet``, the
  297. ``pet`` :class:`class_` instance must be supplied to the :class:`enum_`.
  298. constructor. The :func:`enum_::export_values` function exports the enum entries
  299. into the parent scope, which should be skipped for newer C++11-style strongly
  300. typed enums.
  301. .. code-block:: pycon
  302. >>> p = Pet('Lucy', Pet.Cat)
  303. >>> p.type
  304. Kind.Cat
  305. >>> int(p.type)
  306. 1L
  307. The entries defined by the enumeration type are exposed in the ``__members__`` property:
  308. .. code-block:: pycon
  309. >>> Pet.Kind.__members__
  310. {'Dog': Kind.Dog, 'Cat': Kind.Cat}
  311. .. note::
  312. When the special tag ``py::arithmetic()`` is specified to the ``enum_``
  313. constructor, pybind11 creates an enumeration that also supports rudimentary
  314. arithmetic and bit-level operations like comparisons, and, or, xor, negation,
  315. etc.
  316. .. code-block:: cpp
  317. py::enum_<Pet::Kind>(pet, "Kind", py::arithmetic())
  318. ...
  319. By default, these are omitted to conserve space.