Wenzel Jakob | 28f98aa | 2015-10-13 02:57:16 +0200 | [diff] [blame] | 1 | .. _classes: |
| 2 | |
| 3 | Object-oriented code |
| 4 | #################### |
| 5 | |
| 6 | Creating bindings for a custom type |
| 7 | =================================== |
| 8 | |
| 9 | Let's now look at a more complex example where we'll create bindings for a |
| 10 | custom C++ data structure named ``Pet``. Its definition is given below: |
| 11 | |
| 12 | .. code-block:: cpp |
| 13 | |
| 14 | struct Pet { |
| 15 | Pet(const std::string &name) : name(name) { } |
| 16 | void setName(const std::string &name_) { name = name_; } |
| 17 | const std::string &getName() const { return name; } |
| 18 | |
| 19 | std::string name; |
| 20 | }; |
| 21 | |
| 22 | The binding code for ``Pet`` looks as follows: |
| 23 | |
| 24 | .. code-block:: cpp |
| 25 | |
Wenzel Jakob | 8f4eb00 | 2015-10-15 18:13:33 +0200 | [diff] [blame] | 26 | #include <pybind11/pybind11.h> |
Wenzel Jakob | 9329669 | 2015-10-13 23:21:54 +0200 | [diff] [blame] | 27 | |
Wenzel Jakob | 10e62e1 | 2015-10-15 22:46:07 +0200 | [diff] [blame] | 28 | namespace py = pybind11; |
Wenzel Jakob | 28f98aa | 2015-10-13 02:57:16 +0200 | [diff] [blame] | 29 | |
Wenzel Jakob | b1b7140 | 2015-10-18 16:48:30 +0200 | [diff] [blame] | 30 | PYBIND11_PLUGIN(example) { |
Wenzel Jakob | 8f4eb00 | 2015-10-15 18:13:33 +0200 | [diff] [blame] | 31 | py::module m("example", "pybind11 example plugin"); |
Wenzel Jakob | 28f98aa | 2015-10-13 02:57:16 +0200 | [diff] [blame] | 32 | |
| 33 | py::class_<Pet>(m, "Pet") |
| 34 | .def(py::init<const std::string &>()) |
| 35 | .def("setName", &Pet::setName) |
| 36 | .def("getName", &Pet::getName); |
| 37 | |
| 38 | return m.ptr(); |
| 39 | } |
| 40 | |
| 41 | :class:`class_` creates bindings for a C++ `class` or `struct`-style data |
| 42 | structure. :func:`init` is a convenience function that takes the types of a |
| 43 | constructor's parameters as template arguments and wraps the corresponding |
| 44 | constructor (see the :ref:`custom_constructors` section for details). An |
| 45 | interactive Python session demonstrating this example is shown below: |
| 46 | |
Wenzel Jakob | 99279f7 | 2016-06-03 11:19:29 +0200 | [diff] [blame] | 47 | .. code-block:: pycon |
Wenzel Jakob | 28f98aa | 2015-10-13 02:57:16 +0200 | [diff] [blame] | 48 | |
| 49 | % python |
| 50 | >>> import example |
| 51 | >>> p = example.Pet('Molly') |
| 52 | >>> print(p) |
| 53 | <example.Pet object at 0x10cd98060> |
| 54 | >>> p.getName() |
| 55 | u'Molly' |
| 56 | >>> p.setName('Charly') |
| 57 | >>> p.getName() |
| 58 | u'Charly' |
| 59 | |
Wenzel Jakob | 43b6a23 | 2016-02-07 17:24:41 +0100 | [diff] [blame] | 60 | .. seealso:: |
| 61 | |
| 62 | Static member functions can be bound in the same way using |
| 63 | :func:`class_::def_static`. |
| 64 | |
Wenzel Jakob | 28f98aa | 2015-10-13 02:57:16 +0200 | [diff] [blame] | 65 | Keyword and default arguments |
| 66 | ============================= |
| 67 | It is possible to specify keyword and default arguments using the syntax |
| 68 | discussed in the previous chapter. Refer to the sections :ref:`keyword_args` |
| 69 | and :ref:`default_args` for details. |
| 70 | |
| 71 | Binding lambda functions |
| 72 | ======================== |
| 73 | |
| 74 | Note how ``print(p)`` produced a rather useless summary of our data structure in the example above: |
| 75 | |
Wenzel Jakob | 99279f7 | 2016-06-03 11:19:29 +0200 | [diff] [blame] | 76 | .. code-block:: pycon |
Wenzel Jakob | 28f98aa | 2015-10-13 02:57:16 +0200 | [diff] [blame] | 77 | |
| 78 | >>> print(p) |
| 79 | <example.Pet object at 0x10cd98060> |
| 80 | |
| 81 | To address this, we could bind an utility function that returns a human-readable |
| 82 | summary to the special method slot named ``__repr__``. Unfortunately, there is no |
| 83 | suitable functionality in the ``Pet`` data structure, and it would be nice if |
| 84 | we did not have to change it. This can easily be accomplished by binding a |
| 85 | Lambda function instead: |
| 86 | |
| 87 | .. code-block:: cpp |
| 88 | |
| 89 | py::class_<Pet>(m, "Pet") |
| 90 | .def(py::init<const std::string &>()) |
| 91 | .def("setName", &Pet::setName) |
| 92 | .def("getName", &Pet::getName) |
| 93 | .def("__repr__", |
| 94 | [](const Pet &a) { |
| 95 | return "<example.Pet named '" + a.name + "'>"; |
| 96 | } |
| 97 | ); |
| 98 | |
| 99 | Both stateless [#f1]_ and stateful lambda closures are supported by pybind11. |
| 100 | With the above change, the same Python code now produces the following output: |
| 101 | |
Wenzel Jakob | 99279f7 | 2016-06-03 11:19:29 +0200 | [diff] [blame] | 102 | .. code-block:: pycon |
Wenzel Jakob | 28f98aa | 2015-10-13 02:57:16 +0200 | [diff] [blame] | 103 | |
| 104 | >>> print(p) |
| 105 | <example.Pet named 'Molly'> |
| 106 | |
Wenzel Jakob | f88af0c | 2016-06-22 13:52:31 +0200 | [diff] [blame] | 107 | .. _properties: |
| 108 | |
Wenzel Jakob | 28f98aa | 2015-10-13 02:57:16 +0200 | [diff] [blame] | 109 | Instance and static fields |
| 110 | ========================== |
| 111 | |
| 112 | We can also directly expose the ``name`` field using the |
| 113 | :func:`class_::def_readwrite` method. A similar :func:`class_::def_readonly` |
| 114 | method also exists for ``const`` fields. |
| 115 | |
| 116 | .. code-block:: cpp |
| 117 | |
| 118 | py::class_<Pet>(m, "Pet") |
| 119 | .def(py::init<const std::string &>()) |
| 120 | .def_readwrite("name", &Pet::name) |
| 121 | // ... remainder ... |
| 122 | |
| 123 | This makes it possible to write |
| 124 | |
Wenzel Jakob | 99279f7 | 2016-06-03 11:19:29 +0200 | [diff] [blame] | 125 | .. code-block:: pycon |
Wenzel Jakob | 28f98aa | 2015-10-13 02:57:16 +0200 | [diff] [blame] | 126 | |
| 127 | >>> p = example.Pet('Molly') |
| 128 | >>> p.name |
| 129 | u'Molly' |
| 130 | >>> p.name = 'Charly' |
| 131 | >>> p.name |
| 132 | u'Charly' |
| 133 | |
| 134 | Now suppose that ``Pet::name`` was a private internal variable |
| 135 | that can only be accessed via setters and getters. |
| 136 | |
| 137 | .. code-block:: cpp |
| 138 | |
| 139 | class Pet { |
| 140 | public: |
| 141 | Pet(const std::string &name) : name(name) { } |
| 142 | void setName(const std::string &name_) { name = name_; } |
| 143 | const std::string &getName() const { return name; } |
| 144 | private: |
| 145 | std::string name; |
| 146 | }; |
| 147 | |
| 148 | In this case, the method :func:`class_::def_property` |
| 149 | (:func:`class_::def_property_readonly` for read-only data) can be used to |
Wenzel Jakob | 9329669 | 2015-10-13 23:21:54 +0200 | [diff] [blame] | 150 | provide a field-like interface within Python that will transparently call |
| 151 | the setter and getter functions: |
Wenzel Jakob | 28f98aa | 2015-10-13 02:57:16 +0200 | [diff] [blame] | 152 | |
| 153 | .. code-block:: cpp |
| 154 | |
| 155 | py::class_<Pet>(m, "Pet") |
| 156 | .def(py::init<const std::string &>()) |
| 157 | .def_property("name", &Pet::getName, &Pet::setName) |
| 158 | // ... remainder ... |
| 159 | |
| 160 | .. seealso:: |
| 161 | |
| 162 | Similar functions :func:`class_::def_readwrite_static`, |
| 163 | :func:`class_::def_readonly_static` :func:`class_::def_property_static`, |
| 164 | and :func:`class_::def_property_readonly_static` are provided for binding |
Wenzel Jakob | f88af0c | 2016-06-22 13:52:31 +0200 | [diff] [blame] | 165 | static variables and properties. Please also see the section on |
| 166 | :ref:`static_properties` in the advanced part of the documentation. |
Wenzel Jakob | 28f98aa | 2015-10-13 02:57:16 +0200 | [diff] [blame] | 167 | |
Dean Moldovan | 9273af4 | 2016-10-13 23:53:16 +0200 | [diff] [blame] | 168 | Dynamic attributes |
| 169 | ================== |
| 170 | |
| 171 | Native Python classes can pick up new attributes dynamically: |
| 172 | |
| 173 | .. code-block:: pycon |
| 174 | |
| 175 | >>> class Pet: |
| 176 | ... name = 'Molly' |
| 177 | ... |
| 178 | >>> p = Pet() |
| 179 | >>> p.name = 'Charly' # overwrite existing |
| 180 | >>> p.age = 2 # dynamically add a new attribute |
| 181 | |
| 182 | By default, classes exported from C++ do not support this and the only writable |
| 183 | attributes are the ones explicitly defined using :func:`class_::def_readwrite` |
| 184 | or :func:`class_::def_property`. |
| 185 | |
| 186 | .. code-block:: cpp |
| 187 | |
| 188 | py::class_<Pet>(m, "Pet") |
| 189 | .def(py::init<>()) |
| 190 | .def_readwrite("name", &Pet::name); |
| 191 | |
| 192 | Trying to set any other attribute results in an error: |
| 193 | |
| 194 | .. code-block:: pycon |
| 195 | |
| 196 | >>> p = example.Pet() |
| 197 | >>> p.name = 'Charly' # OK, attribute defined in C++ |
| 198 | >>> p.age = 2 # fail |
| 199 | AttributeError: 'Pet' object has no attribute 'age' |
| 200 | |
| 201 | To enable dynamic attributes for C++ classes, the :class:`py::dynamic_attr` tag |
| 202 | must be added to the :class:`py::class_` constructor: |
| 203 | |
| 204 | .. code-block:: cpp |
| 205 | |
| 206 | py::class_<Pet>(m, "Pet", py::dynamic_attr()) |
| 207 | .def(py::init<>()) |
| 208 | .def_readwrite("name", &Pet::name); |
| 209 | |
| 210 | Now everything works as expected: |
| 211 | |
| 212 | .. code-block:: pycon |
| 213 | |
| 214 | >>> p = example.Pet() |
| 215 | >>> p.name = 'Charly' # OK, overwrite value in C++ |
| 216 | >>> p.age = 2 # OK, dynamically add a new attribute |
| 217 | >>> p.__dict__ # just like a native Python class |
| 218 | {'age': 2} |
| 219 | |
| 220 | Note that there is a small runtime cost for a class with dynamic attributes. |
| 221 | Not only because of the addition of a ``__dict__``, but also because of more |
| 222 | expensive garbage collection tracking which must be activated to resolve |
| 223 | possible circular references. Native Python classes incur this same cost by |
| 224 | default, so this is not anything to worry about. By default, pybind11 classes |
| 225 | are more efficient than native Python classes. Enabling dynamic attributes |
| 226 | just brings them on par. |
| 227 | |
Wenzel Jakob | 2dfbade | 2016-01-17 22:36:37 +0100 | [diff] [blame] | 228 | .. _inheritance: |
| 229 | |
Wenzel Jakob | 28f98aa | 2015-10-13 02:57:16 +0200 | [diff] [blame] | 230 | Inheritance |
| 231 | =========== |
| 232 | |
| 233 | Suppose now that the example consists of two data structures with an |
| 234 | inheritance relationship: |
| 235 | |
| 236 | .. code-block:: cpp |
| 237 | |
| 238 | struct Pet { |
| 239 | Pet(const std::string &name) : name(name) { } |
| 240 | std::string name; |
| 241 | }; |
| 242 | |
| 243 | struct Dog : Pet { |
| 244 | Dog(const std::string &name) : Pet(name) { } |
| 245 | std::string bark() const { return "woof!"; } |
| 246 | }; |
| 247 | |
Wenzel Jakob | bad589a | 2016-09-12 12:03:20 +0900 | [diff] [blame] | 248 | There are two different ways of indicating a hierarchical relationship to |
Jason Rhinelander | 6b52c83 | 2016-09-06 12:27:00 -0400 | [diff] [blame] | 249 | pybind11: the first specifies the C++ base class as an extra template |
Wenzel Jakob | bad589a | 2016-09-12 12:03:20 +0900 | [diff] [blame] | 250 | parameter of the :class:`class_`: |
Wenzel Jakob | 48548ea | 2016-01-17 22:36:44 +0100 | [diff] [blame] | 251 | |
| 252 | .. code-block:: cpp |
| 253 | |
| 254 | py::class_<Pet>(m, "Pet") |
| 255 | .def(py::init<const std::string &>()) |
| 256 | .def_readwrite("name", &Pet::name); |
| 257 | |
Jason Rhinelander | 6b52c83 | 2016-09-06 12:27:00 -0400 | [diff] [blame] | 258 | // Method 1: template parameter: |
| 259 | py::class_<Dog, Pet /* <- specify C++ parent type */>(m, "Dog") |
| 260 | .def(py::init<const std::string &>()) |
| 261 | .def("bark", &Dog::bark); |
| 262 | |
Wenzel Jakob | 48548ea | 2016-01-17 22:36:44 +0100 | [diff] [blame] | 263 | Alternatively, we can also assign a name to the previously bound ``Pet`` |
| 264 | :class:`class_` object and reference it when binding the ``Dog`` class: |
Wenzel Jakob | 28f98aa | 2015-10-13 02:57:16 +0200 | [diff] [blame] | 265 | |
| 266 | .. code-block:: cpp |
| 267 | |
| 268 | py::class_<Pet> pet(m, "Pet"); |
| 269 | pet.def(py::init<const std::string &>()) |
| 270 | .def_readwrite("name", &Pet::name); |
| 271 | |
Wenzel Jakob | bad589a | 2016-09-12 12:03:20 +0900 | [diff] [blame] | 272 | // Method 2: pass parent class_ object: |
Wenzel Jakob | 48548ea | 2016-01-17 22:36:44 +0100 | [diff] [blame] | 273 | py::class_<Dog>(m, "Dog", pet /* <- specify Python parent type */) |
Wenzel Jakob | 28f98aa | 2015-10-13 02:57:16 +0200 | [diff] [blame] | 274 | .def(py::init<const std::string &>()) |
| 275 | .def("bark", &Dog::bark); |
| 276 | |
Wenzel Jakob | bad589a | 2016-09-12 12:03:20 +0900 | [diff] [blame] | 277 | Functionality-wise, both approaches are equivalent. Afterwards, instances will |
| 278 | expose fields and methods of both types: |
Wenzel Jakob | 28f98aa | 2015-10-13 02:57:16 +0200 | [diff] [blame] | 279 | |
Wenzel Jakob | 99279f7 | 2016-06-03 11:19:29 +0200 | [diff] [blame] | 280 | .. code-block:: pycon |
Wenzel Jakob | 28f98aa | 2015-10-13 02:57:16 +0200 | [diff] [blame] | 281 | |
| 282 | >>> p = example.Dog('Molly') |
| 283 | >>> p.name |
| 284 | u'Molly' |
| 285 | >>> p.bark() |
| 286 | u'woof!' |
| 287 | |
| 288 | Overloaded methods |
| 289 | ================== |
| 290 | |
| 291 | Sometimes there are several overloaded C++ methods with the same name taking |
| 292 | different kinds of input arguments: |
| 293 | |
| 294 | .. code-block:: cpp |
| 295 | |
| 296 | struct Pet { |
| 297 | Pet(const std::string &name, int age) : name(name), age(age) { } |
| 298 | |
| 299 | void set(int age) { age = age; } |
| 300 | void set(const std::string &name) { name = name; } |
| 301 | |
| 302 | std::string name; |
| 303 | int age; |
| 304 | }; |
| 305 | |
| 306 | Attempting to bind ``Pet::set`` will cause an error since the compiler does not |
| 307 | know which method the user intended to select. We can disambiguate by casting |
| 308 | them to function pointers. Binding multiple functions to the same Python name |
Wenzel Jakob | 0fb8528 | 2015-10-19 23:50:51 +0200 | [diff] [blame] | 309 | automatically creates a chain of function overloads that will be tried in |
Wenzel Jakob | 28f98aa | 2015-10-13 02:57:16 +0200 | [diff] [blame] | 310 | sequence. |
| 311 | |
| 312 | .. code-block:: cpp |
| 313 | |
| 314 | py::class_<Pet>(m, "Pet") |
| 315 | .def(py::init<const std::string &, int>()) |
| 316 | .def("set", (void (Pet::*)(int)) &Pet::set, "Set the pet's age") |
| 317 | .def("set", (void (Pet::*)(const std::string &)) &Pet::set, "Set the pet's name"); |
| 318 | |
| 319 | The overload signatures are also visible in the method's docstring: |
| 320 | |
Wenzel Jakob | 99279f7 | 2016-06-03 11:19:29 +0200 | [diff] [blame] | 321 | .. code-block:: pycon |
Wenzel Jakob | 28f98aa | 2015-10-13 02:57:16 +0200 | [diff] [blame] | 322 | |
| 323 | >>> help(example.Pet) |
| 324 | |
| 325 | class Pet(__builtin__.object) |
| 326 | | Methods defined here: |
| 327 | | |
| 328 | | __init__(...) |
Wenzel Jakob | 48548ea | 2016-01-17 22:36:44 +0100 | [diff] [blame] | 329 | | Signature : (Pet, str, int) -> NoneType |
Wenzel Jakob | 28f98aa | 2015-10-13 02:57:16 +0200 | [diff] [blame] | 330 | | |
| 331 | | set(...) |
Wenzel Jakob | 48548ea | 2016-01-17 22:36:44 +0100 | [diff] [blame] | 332 | | 1. Signature : (Pet, int) -> NoneType |
Wenzel Jakob | 28f98aa | 2015-10-13 02:57:16 +0200 | [diff] [blame] | 333 | | |
| 334 | | Set the pet's age |
| 335 | | |
Wenzel Jakob | 48548ea | 2016-01-17 22:36:44 +0100 | [diff] [blame] | 336 | | 2. Signature : (Pet, str) -> NoneType |
Wenzel Jakob | 28f98aa | 2015-10-13 02:57:16 +0200 | [diff] [blame] | 337 | | |
| 338 | | Set the pet's name |
Wenzel Jakob | 9329669 | 2015-10-13 23:21:54 +0200 | [diff] [blame] | 339 | |
| 340 | .. note:: |
| 341 | |
| 342 | To define multiple overloaded constructors, simply declare one after the |
| 343 | other using the ``.def(py::init<...>())`` syntax. The existing machinery |
| 344 | for specifying keyword and default arguments also works. |
Wenzel Jakob | 28f98aa | 2015-10-13 02:57:16 +0200 | [diff] [blame] | 345 | |
| 346 | Enumerations and internal types |
| 347 | =============================== |
| 348 | |
Wenzel Jakob | 9329669 | 2015-10-13 23:21:54 +0200 | [diff] [blame] | 349 | Let's now suppose that the example class contains an internal enumeration type, |
| 350 | e.g.: |
Wenzel Jakob | 28f98aa | 2015-10-13 02:57:16 +0200 | [diff] [blame] | 351 | |
| 352 | .. code-block:: cpp |
| 353 | |
| 354 | struct Pet { |
| 355 | enum Kind { |
| 356 | Dog = 0, |
| 357 | Cat |
| 358 | }; |
| 359 | |
| 360 | Pet(const std::string &name, Kind type) : name(name), type(type) { } |
| 361 | |
| 362 | std::string name; |
| 363 | Kind type; |
| 364 | }; |
| 365 | |
| 366 | The binding code for this example looks as follows: |
| 367 | |
| 368 | .. code-block:: cpp |
| 369 | |
| 370 | py::class_<Pet> pet(m, "Pet"); |
| 371 | |
| 372 | pet.def(py::init<const std::string &, Pet::Kind>()) |
| 373 | .def_readwrite("name", &Pet::name) |
| 374 | .def_readwrite("type", &Pet::type); |
| 375 | |
| 376 | py::enum_<Pet::Kind>(pet, "Kind") |
| 377 | .value("Dog", Pet::Kind::Dog) |
| 378 | .value("Cat", Pet::Kind::Cat) |
| 379 | .export_values(); |
| 380 | |
| 381 | To ensure that the ``Kind`` type is created within the scope of ``Pet``, the |
| 382 | ``pet`` :class:`class_` instance must be supplied to the :class:`enum_`. |
Wenzel Jakob | 9329669 | 2015-10-13 23:21:54 +0200 | [diff] [blame] | 383 | constructor. The :func:`enum_::export_values` function exports the enum entries |
| 384 | into the parent scope, which should be skipped for newer C++11-style strongly |
| 385 | typed enums. |
Wenzel Jakob | 28f98aa | 2015-10-13 02:57:16 +0200 | [diff] [blame] | 386 | |
Wenzel Jakob | 99279f7 | 2016-06-03 11:19:29 +0200 | [diff] [blame] | 387 | .. code-block:: pycon |
Wenzel Jakob | 28f98aa | 2015-10-13 02:57:16 +0200 | [diff] [blame] | 388 | |
| 389 | >>> p = Pet('Lucy', Pet.Cat) |
| 390 | >>> p.type |
| 391 | Kind.Cat |
| 392 | >>> int(p.type) |
| 393 | 1L |
| 394 | |
| 395 | |
Wenzel Jakob | 9329669 | 2015-10-13 23:21:54 +0200 | [diff] [blame] | 396 | .. [#f1] Stateless closures are those with an empty pair of brackets ``[]`` as the capture object. |