classes.rst 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551
  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. 'Molly'
  38. >>> p.setName("Charly")
  39. >>> p.getName()
  40. 'Charly'
  41. .. seealso::
  42. Static member functions can be bound in the same way using
  43. :func:`class_::def_static`.
  44. .. note::
  45. Binding C++ types in unnamed namespaces (also known as anonymous namespaces)
  46. works reliably on many platforms, but not all. The `XFAIL_CONDITION` in
  47. tests/test_unnamed_namespace_a.py encodes the currently known conditions.
  48. For background see `#4319 <https://github.com/pybind/pybind11/pull/4319>`_.
  49. If portability is a concern, it is therefore not recommended to bind C++
  50. types in unnamed namespaces. It will be safest to manually pick unique
  51. namespace names.
  52. Keyword and default arguments
  53. =============================
  54. It is possible to specify keyword and default arguments using the syntax
  55. discussed in the previous chapter. Refer to the sections :ref:`keyword_args`
  56. and :ref:`default_args` for details.
  57. Binding lambda functions
  58. ========================
  59. Note how ``print(p)`` produced a rather useless summary of our data structure in the example above:
  60. .. code-block:: pycon
  61. >>> print(p)
  62. <example.Pet object at 0x10cd98060>
  63. To address this, we could bind a utility function that returns a human-readable
  64. summary to the special method slot named ``__repr__``. Unfortunately, there is no
  65. suitable functionality in the ``Pet`` data structure, and it would be nice if
  66. we did not have to change it. This can easily be accomplished by binding a
  67. Lambda function instead:
  68. .. code-block:: cpp
  69. py::class_<Pet>(m, "Pet")
  70. .def(py::init<const std::string &>())
  71. .def("setName", &Pet::setName)
  72. .def("getName", &Pet::getName)
  73. .def("__repr__",
  74. [](const Pet &a) {
  75. return "<example.Pet named '" + a.name + "'>";
  76. }
  77. );
  78. Both stateless [#f1]_ and stateful lambda closures are supported by pybind11.
  79. With the above change, the same Python code now produces the following output:
  80. .. code-block:: pycon
  81. >>> print(p)
  82. <example.Pet named 'Molly'>
  83. .. [#f1] Stateless closures are those with an empty pair of brackets ``[]`` as the capture object.
  84. .. _properties:
  85. Instance and static fields
  86. ==========================
  87. We can also directly expose the ``name`` field using the
  88. :func:`class_::def_readwrite` method. A similar :func:`class_::def_readonly`
  89. method also exists for ``const`` fields.
  90. .. code-block:: cpp
  91. py::class_<Pet>(m, "Pet")
  92. .def(py::init<const std::string &>())
  93. .def_readwrite("name", &Pet::name)
  94. // ... remainder ...
  95. This makes it possible to write
  96. .. code-block:: pycon
  97. >>> p = example.Pet("Molly")
  98. >>> p.name
  99. 'Molly'
  100. >>> p.name = "Charly"
  101. >>> p.name
  102. 'Charly'
  103. Now suppose that ``Pet::name`` was a private internal variable
  104. that can only be accessed via setters and getters.
  105. .. code-block:: cpp
  106. class Pet {
  107. public:
  108. Pet(const std::string &name) : name(name) { }
  109. void setName(const std::string &name_) { name = name_; }
  110. const std::string &getName() const { return name; }
  111. private:
  112. std::string name;
  113. };
  114. In this case, the method :func:`class_::def_property`
  115. (:func:`class_::def_property_readonly` for read-only data) can be used to
  116. provide a field-like interface within Python that will transparently call
  117. the setter and getter functions:
  118. .. code-block:: cpp
  119. py::class_<Pet>(m, "Pet")
  120. .def(py::init<const std::string &>())
  121. .def_property("name", &Pet::getName, &Pet::setName)
  122. // ... remainder ...
  123. Write only properties can be defined by passing ``nullptr`` as the
  124. input for the read function.
  125. .. seealso::
  126. Similar functions :func:`class_::def_readwrite_static`,
  127. :func:`class_::def_readonly_static` :func:`class_::def_property_static`,
  128. and :func:`class_::def_property_readonly_static` are provided for binding
  129. static variables and properties. Please also see the section on
  130. :ref:`static_properties` in the advanced part of the documentation.
  131. Dynamic attributes
  132. ==================
  133. Native Python classes can pick up new attributes dynamically:
  134. .. code-block:: pycon
  135. >>> class Pet:
  136. ... name = "Molly"
  137. ...
  138. >>> p = Pet()
  139. >>> p.name = "Charly" # overwrite existing
  140. >>> p.age = 2 # dynamically add a new attribute
  141. By default, classes exported from C++ do not support this and the only writable
  142. attributes are the ones explicitly defined using :func:`class_::def_readwrite`
  143. or :func:`class_::def_property`.
  144. .. code-block:: cpp
  145. py::class_<Pet>(m, "Pet")
  146. .def(py::init<>())
  147. .def_readwrite("name", &Pet::name);
  148. Trying to set any other attribute results in an error:
  149. .. code-block:: pycon
  150. >>> p = example.Pet()
  151. >>> p.name = "Charly" # OK, attribute defined in C++
  152. >>> p.age = 2 # fail
  153. AttributeError: 'Pet' object has no attribute 'age'
  154. To enable dynamic attributes for C++ classes, the :class:`py::dynamic_attr` tag
  155. must be added to the :class:`py::class_` constructor:
  156. .. code-block:: cpp
  157. py::class_<Pet>(m, "Pet", py::dynamic_attr())
  158. .def(py::init<>())
  159. .def_readwrite("name", &Pet::name);
  160. Now everything works as expected:
  161. .. code-block:: pycon
  162. >>> p = example.Pet()
  163. >>> p.name = "Charly" # OK, overwrite value in C++
  164. >>> p.age = 2 # OK, dynamically add a new attribute
  165. >>> p.__dict__ # just like a native Python class
  166. {'age': 2}
  167. Note that there is a small runtime cost for a class with dynamic attributes.
  168. Not only because of the addition of a ``__dict__``, but also because of more
  169. expensive garbage collection tracking which must be activated to resolve
  170. possible circular references. Native Python classes incur this same cost by
  171. default, so this is not anything to worry about. By default, pybind11 classes
  172. are more efficient than native Python classes. Enabling dynamic attributes
  173. just brings them on par.
  174. .. _inheritance:
  175. Inheritance and automatic downcasting
  176. =====================================
  177. Suppose now that the example consists of two data structures with an
  178. inheritance relationship:
  179. .. code-block:: cpp
  180. struct Pet {
  181. Pet(const std::string &name) : name(name) { }
  182. std::string name;
  183. };
  184. struct Dog : Pet {
  185. Dog(const std::string &name) : Pet(name) { }
  186. std::string bark() const { return "woof!"; }
  187. };
  188. There are two different ways of indicating a hierarchical relationship to
  189. pybind11: the first specifies the C++ base class as an extra template
  190. parameter of the :class:`class_`:
  191. .. code-block:: cpp
  192. py::class_<Pet>(m, "Pet")
  193. .def(py::init<const std::string &>())
  194. .def_readwrite("name", &Pet::name);
  195. // Method 1: template parameter:
  196. py::class_<Dog, Pet /* <- specify C++ parent type */>(m, "Dog")
  197. .def(py::init<const std::string &>())
  198. .def("bark", &Dog::bark);
  199. Alternatively, we can also assign a name to the previously bound ``Pet``
  200. :class:`class_` object and reference it when binding the ``Dog`` class:
  201. .. code-block:: cpp
  202. py::class_<Pet> pet(m, "Pet");
  203. pet.def(py::init<const std::string &>())
  204. .def_readwrite("name", &Pet::name);
  205. // Method 2: pass parent class_ object:
  206. py::class_<Dog>(m, "Dog", pet /* <- specify Python parent type */)
  207. .def(py::init<const std::string &>())
  208. .def("bark", &Dog::bark);
  209. Functionality-wise, both approaches are equivalent. Afterwards, instances will
  210. expose fields and methods of both types:
  211. .. code-block:: pycon
  212. >>> p = example.Dog("Molly")
  213. >>> p.name
  214. 'Molly'
  215. >>> p.bark()
  216. 'woof!'
  217. The C++ classes defined above are regular non-polymorphic types with an
  218. inheritance relationship. This is reflected in Python:
  219. .. code-block:: cpp
  220. // Return a base pointer to a derived instance
  221. m.def("pet_store", []() { return std::unique_ptr<Pet>(new Dog("Molly")); });
  222. .. code-block:: pycon
  223. >>> p = example.pet_store()
  224. >>> type(p) # `Dog` instance behind `Pet` pointer
  225. Pet # no pointer downcasting for regular non-polymorphic types
  226. >>> p.bark()
  227. AttributeError: 'Pet' object has no attribute 'bark'
  228. The function returned a ``Dog`` instance, but because it's a non-polymorphic
  229. type behind a base pointer, Python only sees a ``Pet``. In C++, a type is only
  230. considered polymorphic if it has at least one virtual function and pybind11
  231. will automatically recognize this:
  232. .. code-block:: cpp
  233. struct PolymorphicPet {
  234. virtual ~PolymorphicPet() = default;
  235. };
  236. struct PolymorphicDog : PolymorphicPet {
  237. std::string bark() const { return "woof!"; }
  238. };
  239. // Same binding code
  240. py::class_<PolymorphicPet>(m, "PolymorphicPet");
  241. py::class_<PolymorphicDog, PolymorphicPet>(m, "PolymorphicDog")
  242. .def(py::init<>())
  243. .def("bark", &PolymorphicDog::bark);
  244. // Again, return a base pointer to a derived instance
  245. m.def("pet_store2", []() { return std::unique_ptr<PolymorphicPet>(new PolymorphicDog); });
  246. .. code-block:: pycon
  247. >>> p = example.pet_store2()
  248. >>> type(p)
  249. PolymorphicDog # automatically downcast
  250. >>> p.bark()
  251. 'woof!'
  252. Given a pointer to a polymorphic base, pybind11 performs automatic downcasting
  253. to the actual derived type. Note that this goes beyond the usual situation in
  254. C++: we don't just get access to the virtual functions of the base, we get the
  255. concrete derived type including functions and attributes that the base type may
  256. not even be aware of.
  257. .. seealso::
  258. For more information about polymorphic behavior see :ref:`overriding_virtuals`.
  259. Overloaded methods
  260. ==================
  261. Sometimes there are several overloaded C++ methods with the same name taking
  262. different kinds of input arguments:
  263. .. code-block:: cpp
  264. struct Pet {
  265. Pet(const std::string &name, int age) : name(name), age(age) { }
  266. void set(int age_) { age = age_; }
  267. void set(const std::string &name_) { name = name_; }
  268. std::string name;
  269. int age;
  270. };
  271. Attempting to bind ``Pet::set`` will cause an error since the compiler does not
  272. know which method the user intended to select. We can disambiguate by casting
  273. them to function pointers. Binding multiple functions to the same Python name
  274. automatically creates a chain of function overloads that will be tried in
  275. sequence.
  276. .. code-block:: cpp
  277. py::class_<Pet>(m, "Pet")
  278. .def(py::init<const std::string &, int>())
  279. .def("set", static_cast<void (Pet::*)(int)>(&Pet::set), "Set the pet's age")
  280. .def("set", static_cast<void (Pet::*)(const std::string &)>(&Pet::set), "Set the pet's name");
  281. The overload signatures are also visible in the method's docstring:
  282. .. code-block:: pycon
  283. >>> help(example.Pet)
  284. class Pet(__builtin__.object)
  285. | Methods defined here:
  286. |
  287. | __init__(...)
  288. | Signature : (Pet, str, int) -> NoneType
  289. |
  290. | set(...)
  291. | 1. Signature : (Pet, int) -> NoneType
  292. |
  293. | Set the pet's age
  294. |
  295. | 2. Signature : (Pet, str) -> NoneType
  296. |
  297. | Set the pet's name
  298. If you have a C++14 compatible compiler [#cpp14]_, you can use an alternative
  299. syntax to cast the overloaded function:
  300. .. code-block:: cpp
  301. py::class_<Pet>(m, "Pet")
  302. .def("set", py::overload_cast<int>(&Pet::set), "Set the pet's age")
  303. .def("set", py::overload_cast<const std::string &>(&Pet::set), "Set the pet's name");
  304. Here, ``py::overload_cast`` only requires the parameter types to be specified.
  305. The return type and class are deduced. This avoids the additional noise of
  306. ``void (Pet::*)()`` as seen in the raw cast. If a function is overloaded based
  307. on constness, the ``py::const_`` tag should be used:
  308. .. code-block:: cpp
  309. struct Widget {
  310. int foo(int x, float y);
  311. int foo(int x, float y) const;
  312. };
  313. py::class_<Widget>(m, "Widget")
  314. .def("foo_mutable", py::overload_cast<int, float>(&Widget::foo))
  315. .def("foo_const", py::overload_cast<int, float>(&Widget::foo, py::const_));
  316. If you prefer the ``py::overload_cast`` syntax but have a C++11 compatible compiler only,
  317. you can use ``py::detail::overload_cast_impl`` with an additional set of parentheses:
  318. .. code-block:: cpp
  319. template <typename... Args>
  320. using overload_cast_ = pybind11::detail::overload_cast_impl<Args...>;
  321. py::class_<Pet>(m, "Pet")
  322. .def("set", overload_cast_<int>()(&Pet::set), "Set the pet's age")
  323. .def("set", overload_cast_<const std::string &>()(&Pet::set), "Set the pet's name");
  324. .. [#cpp14] A compiler which supports the ``-std=c++14`` flag.
  325. .. note::
  326. To define multiple overloaded constructors, simply declare one after the
  327. other using the ``.def(py::init<...>())`` syntax. The existing machinery
  328. for specifying keyword and default arguments also works.
  329. Enumerations and internal types
  330. ===============================
  331. Let's now suppose that the example class contains internal types like enumerations, e.g.:
  332. .. code-block:: cpp
  333. struct Pet {
  334. enum Kind {
  335. Dog = 0,
  336. Cat
  337. };
  338. struct Attributes {
  339. float age = 0;
  340. };
  341. Pet(const std::string &name, Kind type) : name(name), type(type) { }
  342. std::string name;
  343. Kind type;
  344. Attributes attr;
  345. };
  346. The binding code for this example looks as follows:
  347. .. code-block:: cpp
  348. py::class_<Pet> pet(m, "Pet");
  349. pet.def(py::init<const std::string &, Pet::Kind>())
  350. .def_readwrite("name", &Pet::name)
  351. .def_readwrite("type", &Pet::type)
  352. .def_readwrite("attr", &Pet::attr);
  353. py::enum_<Pet::Kind>(pet, "Kind")
  354. .value("Dog", Pet::Kind::Dog)
  355. .value("Cat", Pet::Kind::Cat)
  356. .export_values();
  357. py::class_<Pet::Attributes>(pet, "Attributes")
  358. .def(py::init<>())
  359. .def_readwrite("age", &Pet::Attributes::age);
  360. To ensure that the nested types ``Kind`` and ``Attributes`` are created within the scope of ``Pet``, the
  361. ``pet`` :class:`class_` instance must be supplied to the :class:`enum_` and :class:`class_`
  362. constructor. The :func:`enum_::export_values` function exports the enum entries
  363. into the parent scope, which should be skipped for newer C++11-style strongly
  364. typed enums.
  365. .. code-block:: pycon
  366. >>> p = Pet("Lucy", Pet.Cat)
  367. >>> p.type
  368. Kind.Cat
  369. >>> int(p.type)
  370. 1L
  371. The entries defined by the enumeration type are exposed in the ``__members__`` property:
  372. .. code-block:: pycon
  373. >>> Pet.Kind.__members__
  374. {'Dog': Kind.Dog, 'Cat': Kind.Cat}
  375. The ``name`` property returns the name of the enum value as a unicode string.
  376. .. note::
  377. It is also possible to use ``str(enum)``, however these accomplish different
  378. goals. The following shows how these two approaches differ.
  379. .. code-block:: pycon
  380. >>> p = Pet("Lucy", Pet.Cat)
  381. >>> pet_type = p.type
  382. >>> pet_type
  383. Pet.Cat
  384. >>> str(pet_type)
  385. 'Pet.Cat'
  386. >>> pet_type.name
  387. 'Cat'
  388. .. note::
  389. When the special tag ``py::arithmetic()`` is specified to the ``enum_``
  390. constructor, pybind11 creates an enumeration that also supports rudimentary
  391. arithmetic and bit-level operations like comparisons, and, or, xor, negation,
  392. etc.
  393. .. code-block:: cpp
  394. py::enum_<Pet::Kind>(pet, "Kind", py::arithmetic())
  395. ...
  396. By default, these are omitted to conserve space.