classes.rst 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532
  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 a 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. Write only properties can be defined by passing ``nullptr`` as the
  116. input for the read function.
  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 and automatic downcasting
  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. The C++ classes defined above are regular non-polymorphic types with an
  210. inheritance relationship. This is reflected in Python:
  211. .. code-block:: cpp
  212. // Return a base pointer to a derived instance
  213. m.def("pet_store", []() { return std::unique_ptr<Pet>(new Dog("Molly")); });
  214. .. code-block:: pycon
  215. >>> p = example.pet_store()
  216. >>> type(p) # `Dog` instance behind `Pet` pointer
  217. Pet # no pointer downcasting for regular non-polymorphic types
  218. >>> p.bark()
  219. AttributeError: 'Pet' object has no attribute 'bark'
  220. The function returned a ``Dog`` instance, but because it's a non-polymorphic
  221. type behind a base pointer, Python only sees a ``Pet``. In C++, a type is only
  222. considered polymorphic if it has at least one virtual function and pybind11
  223. will automatically recognize this:
  224. .. code-block:: cpp
  225. struct PolymorphicPet {
  226. virtual ~PolymorphicPet() = default;
  227. };
  228. struct PolymorphicDog : PolymorphicPet {
  229. std::string bark() const { return "woof!"; }
  230. };
  231. // Same binding code
  232. py::class_<PolymorphicPet>(m, "PolymorphicPet");
  233. py::class_<PolymorphicDog, PolymorphicPet>(m, "PolymorphicDog")
  234. .def(py::init<>())
  235. .def("bark", &PolymorphicDog::bark);
  236. // Again, return a base pointer to a derived instance
  237. m.def("pet_store2", []() { return std::unique_ptr<PolymorphicPet>(new PolymorphicDog); });
  238. .. code-block:: pycon
  239. >>> p = example.pet_store2()
  240. >>> type(p)
  241. PolymorphicDog # automatically downcast
  242. >>> p.bark()
  243. u'woof!'
  244. Given a pointer to a polymorphic base, pybind11 performs automatic downcasting
  245. to the actual derived type. Note that this goes beyond the usual situation in
  246. C++: we don't just get access to the virtual functions of the base, we get the
  247. concrete derived type including functions and attributes that the base type may
  248. not even be aware of.
  249. .. seealso::
  250. For more information about polymorphic behavior see :ref:`overriding_virtuals`.
  251. Overloaded methods
  252. ==================
  253. Sometimes there are several overloaded C++ methods with the same name taking
  254. different kinds of input arguments:
  255. .. code-block:: cpp
  256. struct Pet {
  257. Pet(const std::string &name, int age) : name(name), age(age) { }
  258. void set(int age_) { age = age_; }
  259. void set(const std::string &name_) { name = name_; }
  260. std::string name;
  261. int age;
  262. };
  263. Attempting to bind ``Pet::set`` will cause an error since the compiler does not
  264. know which method the user intended to select. We can disambiguate by casting
  265. them to function pointers. Binding multiple functions to the same Python name
  266. automatically creates a chain of function overloads that will be tried in
  267. sequence.
  268. .. code-block:: cpp
  269. py::class_<Pet>(m, "Pet")
  270. .def(py::init<const std::string &, int>())
  271. .def("set", static_cast<void (Pet::*)(int)>(&Pet::set), "Set the pet's age")
  272. .def("set", static_cast<void (Pet::*)(const std::string &)>(&Pet::set), "Set the pet's name");
  273. The overload signatures are also visible in the method's docstring:
  274. .. code-block:: pycon
  275. >>> help(example.Pet)
  276. class Pet(__builtin__.object)
  277. | Methods defined here:
  278. |
  279. | __init__(...)
  280. | Signature : (Pet, str, int) -> NoneType
  281. |
  282. | set(...)
  283. | 1. Signature : (Pet, int) -> NoneType
  284. |
  285. | Set the pet's age
  286. |
  287. | 2. Signature : (Pet, str) -> NoneType
  288. |
  289. | Set the pet's name
  290. If you have a C++14 compatible compiler [#cpp14]_, you can use an alternative
  291. syntax to cast the overloaded function:
  292. .. code-block:: cpp
  293. py::class_<Pet>(m, "Pet")
  294. .def("set", py::overload_cast<int>(&Pet::set), "Set the pet's age")
  295. .def("set", py::overload_cast<const std::string &>(&Pet::set), "Set the pet's name");
  296. Here, ``py::overload_cast`` only requires the parameter types to be specified.
  297. The return type and class are deduced. This avoids the additional noise of
  298. ``void (Pet::*)()`` as seen in the raw cast. If a function is overloaded based
  299. on constness, the ``py::const_`` tag should be used:
  300. .. code-block:: cpp
  301. struct Widget {
  302. int foo(int x, float y);
  303. int foo(int x, float y) const;
  304. };
  305. py::class_<Widget>(m, "Widget")
  306. .def("foo_mutable", py::overload_cast<int, float>(&Widget::foo))
  307. .def("foo_const", py::overload_cast<int, float>(&Widget::foo, py::const_));
  308. If you prefer the ``py::overload_cast`` syntax but have a C++11 compatible compiler only,
  309. you can use ``py::detail::overload_cast_impl`` with an additional set of parentheses:
  310. .. code-block:: cpp
  311. template <typename... Args>
  312. using overload_cast_ = pybind11::detail::overload_cast_impl<Args...>;
  313. py::class_<Pet>(m, "Pet")
  314. .def("set", overload_cast_<int>()(&Pet::set), "Set the pet's age")
  315. .def("set", overload_cast_<const std::string &>()(&Pet::set), "Set the pet's name");
  316. .. [#cpp14] A compiler which supports the ``-std=c++14`` flag
  317. or Visual Studio 2015 Update 2 and newer.
  318. .. note::
  319. To define multiple overloaded constructors, simply declare one after the
  320. other using the ``.def(py::init<...>())`` syntax. The existing machinery
  321. for specifying keyword and default arguments also works.
  322. Enumerations and internal types
  323. ===============================
  324. Let's now suppose that the example class contains an internal enumeration type,
  325. e.g.:
  326. .. code-block:: cpp
  327. struct Pet {
  328. enum Kind {
  329. Dog = 0,
  330. Cat
  331. };
  332. Pet(const std::string &name, Kind type) : name(name), type(type) { }
  333. std::string name;
  334. Kind type;
  335. };
  336. The binding code for this example looks as follows:
  337. .. code-block:: cpp
  338. py::class_<Pet> pet(m, "Pet");
  339. pet.def(py::init<const std::string &, Pet::Kind>())
  340. .def_readwrite("name", &Pet::name)
  341. .def_readwrite("type", &Pet::type);
  342. py::enum_<Pet::Kind>(pet, "Kind")
  343. .value("Dog", Pet::Kind::Dog)
  344. .value("Cat", Pet::Kind::Cat)
  345. .export_values();
  346. To ensure that the ``Kind`` type is created within the scope of ``Pet``, the
  347. ``pet`` :class:`class_` instance must be supplied to the :class:`enum_`.
  348. constructor. The :func:`enum_::export_values` function exports the enum entries
  349. into the parent scope, which should be skipped for newer C++11-style strongly
  350. typed enums.
  351. .. code-block:: pycon
  352. >>> p = Pet('Lucy', Pet.Cat)
  353. >>> p.type
  354. Kind.Cat
  355. >>> int(p.type)
  356. 1L
  357. The entries defined by the enumeration type are exposed in the ``__members__`` property:
  358. .. code-block:: pycon
  359. >>> Pet.Kind.__members__
  360. {'Dog': Kind.Dog, 'Cat': Kind.Cat}
  361. The ``name`` property returns the name of the enum value as a unicode string.
  362. .. note::
  363. It is also possible to use ``str(enum)``, however these accomplish different
  364. goals. The following shows how these two approaches differ.
  365. .. code-block:: pycon
  366. >>> p = Pet( "Lucy", Pet.Cat )
  367. >>> pet_type = p.type
  368. >>> pet_type
  369. Pet.Cat
  370. >>> str(pet_type)
  371. 'Pet.Cat'
  372. >>> pet_type.name
  373. 'Cat'
  374. .. note::
  375. When the special tag ``py::arithmetic()`` is specified to the ``enum_``
  376. constructor, pybind11 creates an enumeration that also supports rudimentary
  377. arithmetic and bit-level operations like comparisons, and, or, xor, negation,
  378. etc.
  379. .. code-block:: cpp
  380. py::enum_<Pet::Kind>(pet, "Kind", py::arithmetic())
  381. ...
  382. By default, these are omitted to conserve space.